1
\$\begingroup\$

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?

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

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$
2
  • 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
    Commented May 16, 2018 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
    Commented May 16, 2018 at 21:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .