I am using a Custom Editor Inspector for my MonoBehaviour class and I would like to know I it’s possible to constrain a variable. Let me illustrate this with an example.
Let’s imagine I have an integer value but I would like to authorize only some values in the Inspector like 1, 5, 99, whatever.
I would like to know if there is way to do that for any type of variables using editor features. I know that I can define an Enum or use a Dictionnary with some index but is there another way ?
You can certainly use a custom editor to constrain your variable however you wish. Here is an example of a simple class and editor, where we constrain the public int field to even inputs:
Foo.cs
using UnityEngine;
public class Foo : MonoBehaviour
{
public int Bar;
}
FooEditor.cs
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Foo))]
public class FooEditor : Editor
{
public override void OnInspectorGUI()
{
Foo foo = (Foo)target;
foo.Bar = EditorGUILayout.IntField("Bar", foo.Bar);
foo.Bar = ConstrainBar(foo.Bar);
EditorUtility.SetDirty(foo);
}
int ConstrainBar (int bar)
{
return (int)Mathf.Round((float)bar/2.0f) * 2;
}
}
We don’t really constrain the variable, but instead create an editor that will apply a function to the variable when it is set in the editor. If you want to constrain the variable in code as well, you could have a simple property and apply the constraints in the setter.
Unfortunately, properties (getters/setters) don’t play nice with the inspector by default. There are some hackneyed ways of exposing a property in the inspector, but it’s often unnecessary.