0
\$\begingroup\$

I have an int which I want to be between 0 and an unknown number. This unknown number is max in the example below. I want this max number to change when another number changes in the editor. How can I accomplish this? This is my best attempt, but it won't let me use an unknown value for my range.

[Range(1, 10)]
public int multiplier;

[Range(0, max)]
public int x;

void OnValidate(){
    max = 10 * multiplier;
}
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

GetCustomAttributes will most likely only give you a copy of the original Attribute. Changing that will have no effect at all in the editor.

What you need is a custom inspector: https://unity3d.com/learn/tutorials/modules/intermediate/editor/building-custom-inspector. This will allow you to customize the inspector any way you like.

\$\endgroup\$
0
\$\begingroup\$

You can access and change attributes using reflection, something like:

var attrs = (RangeAttribute[])typeof(myScript).GetCustomAttributes (typeof(RangeAttribute), false);
attrs [0].max = 10;

should work - more or less.
Question is, why would you even wanted that? The only point of Range attribute I see is changing textbox to slider in designer (or is there something more to it?). In case you dont need to access the field in editor you could use properties instead, it even gives you more flexibility(you can define "overflow" logic):

[Range(1, 10)]
public int multiplier;
public int _x;
public int X {
  get { return _x; }
  set { _x = Math.Min(10 * multiplier, value); } //clamp for example
}
\$\endgroup\$
1
  • \$\begingroup\$ I need to access it in inspector. But the max is based on the value of another slider. Specifically, I have a width and height slider. I need the max to be the perimeter of the rectangle created by the width and height. \$\endgroup\$
    – Evorlor
    Commented Dec 28, 2015 at 0:04

You must log in to answer this question.

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