Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Select custom object from a list via PopUp in custom editor for ScriptableObject

Discussion in 'Scripting' started by mrvizious, Jun 21, 2021.

  1. mrvizious

    mrvizious

    Joined:
    Oct 17, 2020
    Posts:
    3
    Hello everybody!

    I have this ScriptableObject named Dialog, which has an attribute of type Character and another one of type Emotion. Here is the diagram:

    unityquestion.png

    What I want is to create a custom editor for the class Dialog, that has a EditorGUILayout.Popup to select the selectedEmotion from the emotions list stored in the character.
    This emotion, character and dialog are all ScriptableObjects and are stored in the Assets folder, so there should be no need to create new assets. Also, if the emotion scriptableObject changes, so should its reference in Dialog.

    I have been pulling my hair for a couple days trying to wrap my head around SerializedProperty(ies), but I simply can't get it to work. I can provide some of my not working code if you want to, too.
    Also, I would prefer not to use target nomenclature and so on, but rather SerializedProperties for better integration.

    Any help at all will be really appreciated, thanks!
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Typed this out in Notepad, so there may be some errors, but hopefully it helps get you started:

    Code (csharp):
    1.  
    2. SerializedProperty emotionList = serializedObject.FindProperty("_emotions"); // replace _emotions with whatever your list variable is called
    3.  
    4. Debug.LogFormat("IsArray: {0} with {1} elements", emotionList.isArray, emotionList.arraySize);
    5.  
    6. if(emotionList.isArray == true)
    7. {
    8.    for(int i = 0; i < emotionList.arraySize; ++i)
    9.    {
    10.        SerializedProperty element = emotionList.GetArrayElementAtIndex(i);
    11.  
    12.        Emotion emotion = element.objectReferenceValue as Emotion;
    13.  
    14.        if(emotion != null)
    15.            Debug.LogFormat("Element {0} is emotion {1}", i, emotion.name);
    16.        else
    17.            Debug.LogFormat("Element {0} failed to cast to emotion", i);
    18.  
    19.        // now you have a reference to your Emotion object and can do whatever you want
    20.    }
    21. }
    22.  
     
  3. mrvizious

    mrvizious

    Joined:
    Oct 17, 2020
    Posts:
    3
    That was really helpful! Turns out I wasn't using ScriptableObjects as Emotion in my implementation.
    Thank you so much, now I understand this much better
     
    GroZZleR likes this.