Show the array in the Inspector (Unity)

妖精的绣舞 提交于 2020-01-15 12:11:07

问题


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


回答1:


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?




回答2:


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 (&rightarrow; there might be mistakes) but I hope the idea gets clear



来源:https://stackoverflow.com/questions/50113211/show-the-array-in-the-inspector-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!