# C# Integer limits for Scriptable Objects

I am experimenting with Scriptable Objects in Unity. In the following example how can I limit the range of accepted values?

public class AScriptableObject : ScriptableObject
{
public uint damage;
}


Since it's a uint the lowest value is 0 but how can I limit the max value to 500 for example? Can I use if statements?

If you want to be able to set it both via editor and script and have it always clamp the value you can write it this way

public class AScriptableObject : ScriptableObject
{
private const int MyMaxValue = 500;
[SerializeField]
[Range(0, MyMaxValue)]
private uint m_damage;

public uint damage
{
get
{
return m_damage;
}
set
{
if (value >= MyMaxValue)
value = MyMaxValue;
m_damage = value;
}
}
}


Note it won't allow you to have MyMaxValue > int.MaxValue because the range attribute only takes in an int, and not a uint

• Hmm, pretty accurate to what I wanted to do. In my case I use [System.Serializable] before public class AScriptableObject : ScriptableObject. Do I need to use [SerializeField] in front of a private uint as well? – Valamorde May 9 '16 at 20:59
• Yes, System.Serializable will tell unity that your class can be serialized, then the SerializeField tells unity to serialize the private field – Colton White May 10 '16 at 17:06
[Range(0,500)] public uint damage;


Should do the trick. This will be show as a slider in the inspector that goes from 0 to 500.

• I am not 100% sure if this is what the OP wants. It limits the value in the editor, but not when set through a script while the game is running. – Philipp May 9 '16 at 14:57
• Well the OP did not specify his use case. Either way the two answers given cover both cases – Uri Popov May 9 '16 at 15:54
• @UriPopov My bad, I thought that leaving it "in general" it would be clear that I meant : in any case. – Valamorde May 9 '16 at 20:57

You can use Unity's MathF.Clamp() method. If you use this method each time you give a value to your integer, it resctricts the value between your min and max values.

For example: if you take a 400 value and use Clamp() method like this;

Mathf.Clamp(400, 0, 300); it returns 300.

http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

• When you want to do something "each time you give a value to your variable", the C# way to do this properly is by declaring the variable private and exposing it through a public property which handles this. – Philipp May 9 '16 at 15:00