Search Unity

How to display GUI components like UnityEvent, Color Gradient etc. for Custom Inspector?

Discussion in 'Immediate Mode GUI (IMGUI)' started by elmar1028, Jan 17, 2016.

  1. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,359
    Hi guys,

    While it's very easy to get UnityEvent or Gradient variables being displayed in inspectors for MonoDevelop scripts, it's quite hard to get it on the custom inspector without using base.OnInspectorGUI (which is not what I want).

    Any ideas?

    Thanks in advance! :)
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,697
    EditorGUI.PropertyField (or EditorGUILayout.PropertyField).

    Code (csharp):
    1. public MyScript : MonoBehaviour {
    2.     Color myColor;
    3. }
    Code (csharp):
    1. [CustomEditor(typeof(MyScript))]
    2. public class MyScriptEditor : Editor {
    3.     public override void OnInspectorGUI() {
    4.         EditorGUILayout.PropertyField(serializedObject.FindProperty("myColor"));
    5.     }
    6. }
     
    Last edited: Jan 21, 2016
  3. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,359
    Thanks! However, I have the following problem.

    I have a list within a list with a custom defined class. So it goes like this:

    LIST1:
    - Variable 1
    - Variable 2
    - LIST2:
    - Variable 3
    - GradientVar

    Variable properties are based on those two LISTS' index number, so the variable itself doesn't remain the same, it's value always changes.

    How do I get Gradient Variable 1 be edited by the PropertyField? I tried doing something like this:

    Code (CSharp):
    1. EditorGUILayout.PropertyField("LIST1[indexNumber].LIST2[indexNumber].GradientVar");
    And obviously, it didn't work.

    Thanks in advance :)
     
  4. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,697
    A SerializedProperty (as returned by serializedObject.FindProperty) can represent an array such as your LIST1. To iterate through it, use GetEnumerator() and MoveNext(). There's a good explanation with code examples on Hamaluik.com.

    However, maybe it would be easier to just use property attributes in your MonoBehaviour definition and forgo the custom inspector. Something like:

    Code (csharp):
    1. [Serializable]
    2. public MyGradientData {
    3.     public bool variable3;
    4.  
    5.     [CustomGradient]
    6.     public Gradient gradientVar;
    7. }
    8.  
    9. [Serializable]
    10. public MyMainData {
    11.     public bool variable1;
    12.     public bool variable2;
    13.     public MyGradientData[] list2;
    14. }
    15.  
    16. public MyScript : MonoBehaviour {
    17.     public MyMainData[] list1;
    18. }
    You'd need to define the custom property attribute "CustomGradient" as described in the Property Drawers manual section.