# How can I set a property for the upper limit for another property's range

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?

• This is using DataAnnotations I assume? – Slagmoth May 16 '18 at 13:11
• @Slagmoth No, I'm not using DataAnnotations – 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.

• 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. – DMGregory May 16 '18 at 19:11
• @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. – Galandil May 16 '18 at 21:50