Search Unity

Unity Editor - Class variable value contrain

Discussion in 'Scripting' started by MaT227, Jan 8, 2015.

  1. MaT227

    MaT227

    Joined:
    Jul 3, 2012
    Posts:
    614
    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.
     
    Last edited: Jan 8, 2015
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,453
    Code (csharp):
    1.  
    2. [SerializeField]
    3. private int someInteger;
    4.  
    5. public int SomeInteger
    6. {
    7.     get
    8.     {
    9.         return someInteger;
    10.     }
    11.     set
    12.     {
    13.         if (value > 10)
    14.             Debug.LogError("someInteger must be less than 10!");
    15.         else
    16.             someInteger = value;
    17.     }
    18. }
    19.  
     
  3. MaT227

    MaT227

    Joined:
    Jul 3, 2012
    Posts:
    614
    @KelsoMRK Thank you for your answer but I would like to do it in the inspector. It's more like an enum but I don't want to use an enum, I would prefere use and editor feature or function. Is it possible ?
     
  4. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,406
  5. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    9,352
    If you're constraining to a range (e.g., 0 to 100), you can use the Range attribute in your MonoBehaviour:
    Code (csharp):
    1. [Range(0,100)]
    2. public int someInteger;
    In your editor class, let Unity draw the property, which will take the attribute into account:
    Code (csharp):
    1. EditorGUILayout.PropertyField(serializedObject.FindProperty("someInteger"));
    If you're really constraining only to specific values (e.g., 1, 5, 99), then you'll definitely need to either write your own property attribute or handle it specially in the custom editor draw method. If you write a property attribute, you can use it more generally, something like:
    Code (csharp):
    1. [ConstrainValues(1,5,99)]
    2. public int someInteger;
     
  6. MaT227

    MaT227

    Joined:
    Jul 3, 2012
    Posts:
    614
    Thanks @LightStriker, EditorGUI.Popup is what I was looking for !
    Thanks @TonyLi I thought that something like [ConstrainValues(1,5,99)] already exist in Unity but I was wrong.