I have two properties, I would like to set one property as the upper limit of another property, hence making the upper rely on a property. As below:

public int fullLength;

[Range(0, fullLength)]
public int segmentLength;

Is there a way to do this, possibly with a custom editor? If yes, how can it be done?

  • \$\begingroup\$ This is using DataAnnotations I assume? \$\endgroup\$ – Slagmoth May 16 '18 at 13:11
  • \$\begingroup\$ @Slagmoth No, I'm not using DataAnnotations \$\endgroup\$ – Bane May 16 '18 at 13:29

It's pretty simple, use OnValidate():

public int fullLength;
public int segmentLength;

private void OnValidate() {
    if (segmentLength < 0) segmentLength = 0;
    else if (segmentLength > fullLength) segmentLength = fullLength;

This method is called (in editor only) whenever the script is loaded or a value is changed in the Inspector.

P.S.: You're not using properties here, you're using fields.

| improve this answer | |
  • 2
    \$\begingroup\$ Note that this won't show a slider widget for varying segmentLength between zero and the max, the way the [Range(0, ...)] attribute used in the question normally would. \$\endgroup\$ – DMGregory May 16 '18 at 19:11
  • \$\begingroup\$ @DMGregory you're right, I don't think that the presence of a slider is of utter importance for OP - it could be implemented anyway, out the top of my head, by using an Editor inheriting script, in which the slider is created in the OnIspectorGUI method and assigned the top value by using a reference to the fullLength variable. But I don't know if such work is really needed, I mean it's just a graphic flavor in the end. \$\endgroup\$ – Galandil May 16 '18 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.