如何展示&在编辑器窗口中修改数组?

时间:2017-12-11 12:49:02

标签: unity3d window editor

我的CustomEditor类中的GameObject数组字段派生自UnityEngine.Editor。我需要能够显示(绘制)并授予用户修改该数组的能力。

就像Unity的Inspector如何为源自ScriptableObject的对象的Serializable字段执行此操作。例如。在检查器中显示材质数组: .

5 个答案:

答案 0 :(得分:1)

关于SerializedObject,请参阅您的编辑器对象,然后找到任何必需的属性,绘制它并应用修改:

public class MyEditorWindow : EditorWindow
{
    [MenuItem("Window/My Editor Window")]
    public static void ShowWindow()
    {
        GetWindow<MyEditorWindow>();
    }

    public string[] Strings = { "Larry", "Curly", "Moe" };

    void OnGUI()
    {
        // "target" can be any class derrived from ScriptableObject 
        // (could be EditorWindow, MonoBehaviour, etc)
        ScriptableObject target = this;
        SerializedObject so = new SerializedObject(target);
        SerializedProperty stringsProperty = so.FindProperty("Strings");

        EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
        so.ApplyModifiedProperties(); // Remember to apply modified properties
    }
}

原始答案here

答案 1 :(得分:0)

public GameObject[] yourGameObjects;

然后在检查员中设置您的尺寸,字段应该打开。

答案 2 :(得分:0)

将一个公共数组添加到您的脚本

public GameObject[] myObjects

答案 3 :(得分:0)

我设法通过一个for循环和一个额外的int来做到这一点:

using UnityEditor;
using UnityEngine;

public class RockSpawner : EditorWindow
{
    int rockCollectionSize = 0;
    GameObject[] rockCollection;

    [MenuItem("Tools/Rock Spawner")]
    public static void ShowWindow()
    {
        GetWindow(typeof(RockSpawner));
    }

    void OnGUI()
    {
        rockCollectionSize = EditorGUILayout.IntField("Rock collection size", rockCollectionSize);
        if (rockCollection != null && rockCollectionSize != rockCollection.Length)
            rockCollection = new GameObject[rockCollectionSize];
        for (int i = 0; i < rockCollectionSize; i++)
        {
            rockCollection[i] = EditorGUILayout.ObjectField("Rock " + i.ToString(), rockCollection[i], typeof(GameObject), false) as GameObject;
        }
    }
}

答案 4 :(得分:0)

最重要的答案对我来说效果不佳,因为属性没有更新,因为我将 decleration 线移动到 OnEnable 函数,您不想一遍又一遍地声明它们)并用于so.Update() 更新更改的变量。


using UnityEngine;
using UnityEditor;
public class MyEditorWindow : EditorWindow
{
    [MenuItem("Window/My Editor Window")]
    public static void ShowWindow()
    {
        GetWindow<MyEditorWindow>();
    }

    public string[] Strings = { "Larry", "Curly", "Moe" };
    SerializedObject so;

    private void OnEnable()
    {
        ScriptableObject target = this;
        so = new SerializedObject(target);
    }

    void OnGUI()
    {
        // "target" can be any class derrived from ScriptableObject 
        // (could be EditorWindow, MonoBehaviour, etc)
        so.Update();
        SerializedProperty stringsProperty = so.FindProperty("Strings");

        EditorGUILayout.PropertyField(stringsProperty, true); // True means show children
        so.ApplyModifiedProperties(); // Remember to apply modified properties
    }
}

链接:

Base for my answer

SerializedObject.Update