- Home /
Unity Editor - Class variable value contrain
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 ?
Thanks a lot.
Answer by Landern · Jan 08, 2015 at 02:02 PM
Use a List of int or an array(int nums[]), get the selected index and return the number from the List/array/Collection.
I've received interesting answer here too : http://forum.unity3d.com/threads/unity-editor-class-variable-value-contrain.289844/
Answer by MakinStuffLookGood · Jan 08, 2015 at 02:42 PM
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.
Answer by Mmmpies · Jan 08, 2015 at 01:56 PM
Setup an enumerator like this
enum TheNumbers
{
1,
5,
99
}
or
enum TheOtherNumbers
{
one,
five,
nintynine
}
I've already thought about making an enum :) but I thought that there was better way to do it using editor features and functions.
enum theNumbers { 1, 5, 99 }
Ah, no, by default an enum type is an int, just like with variables, you can't start it with a number and it represents a number. Given this example if i cast an int to theNumbers.1 it would be 0. But of course that wouldn't work.
Enums: http://msdn.microsoft.com/en-us/library/sbbt4032.aspx