简体   繁体   中英

Show the array in the Inspector (Unity)

I have a list of arrays that I want to show in the inspector

This is my code:

        SerializedProperty ClipArray;
        ClipArray = serializedObject.FindProperty("ClipArray"); // public AudioClip[] ClipArray;



        serializedObject.Update();
        EditorGUILayout.PropertyField(ClipArray);
        serializedObject.ApplyModifiedProperties();

But in the inspector, I show an array without parameters

在此处输入图片说明

Have you tried putting system serializable above the script when you declare your array?

[System.Serializable]
public AudioClip[] ClipArray;

Are any of the values in your array initially set to null?

This is a quite known issue with arrays/lists in custom Editors.

If you checkout EditorGUILayout.PropertyField you will see there are overloads taking a parameter

includeChildren
If true the property including children is drawn; otherwise only the control itself (such as only a foldout but nothing below it) .

so actually all you need to do is passing true like

SerializedProperty ClipArray;

// I would always do these only once ;)
private void OnEnable()
{
    ClipArray = serializedObject.FindProperty("ClipArray");
}

private void OnInspectorGUI ()
{
    serializedObject.Update();
    EditorGUILayout.PropertyField(ClipArray, true);
    serializedObject.ApplyModifiedProperties();
}

As an alternative you could ofcourse also build the entire draw hierachy with the required fields yourself:

private void OnInspectorGUI ()
{
    serializedObject.Update();

    ClipArray.isExpanded = EditorGUILayout.Foldout(ClipArray.isExpanded, ClipArray.name);
    if(ClipArray.isExpanded)
    {
        EditorGUI.indentLevel++;

        // The field for item count
        ClipArray.arraySize = EditorGUILayout.IntField("size", ClipArray.arraySize);

        // draw item fields
        for(var i = 0; i< ClipArray.arraySize; i++)
        {
            var item = ClipArray.GetArrayElementAtIndex(i);
            EditorGUILayout.PropertyField(item, new GUIContent($"Element {i}");
        }

        EditorGUI.indentLevel--;
    }
    serializedObject.ApplyModifiedProperties();
}

I just leave it here since building these kind of stuff manually once helped me a lot to understand how the Editor works.


Note: Typed on smartphone (→ there might be mistakes) but I hope the idea gets clear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM