带有数组的统一自定义编辑器

unity custom editor with arrays

我正在创建游戏,脚本越来越大。为了更清楚,我想使用自定义编辑器。但我对 classes、游戏对象,尤其是数组等类型有疑问。 正如您希望在我的图片中看到的那样,使基本类型(如字符串和浮点数等)可见非常容易。但它如何与数组一起使用?特别是如果数组仍然是 class 或刚体或游戏对象?如果可能的话,我需要一个很好的解释或直接的解决方案。我将非常感谢你的帮助

enter image description here

注意: 如果你只是想 beautify/improve 你的检查员,而不是作为一个实际的 project/experience,你最好正在寻找插件。

Unity提供的Custom-EditorAPI是一堆工具,不是房子。
你最终会付出很多努力来成为你的检查员'look neater'。

如果你只是想创建一个游戏,使用插件来装饰你的检查器。
MyBox 是我使用的插件之一,推荐。

现在回到问题

我设法通过组合使用 EditorGUILayout.Foldout 并遍历数组大小来创建多个 EditorGUILayout.IntField.

来实现它
    // True if the user 'opened' up the array on inspector.
    private bool countIntsOpened;

    public override void OnInspectorGUI() {
        var myTarget = (N_USE)target;

        myTarget.myTest.name = EditorGUILayout.TextField("see name", myTarget.myTest.name);
        myTarget.myTest.countOnly = EditorGUILayout.FloatField("see float", myTarget.myTest.countOnly);

        // Create int array field
        myTarget.myTest.countInts = IntArrayField("see int[]", ref countIntsOpened, myTarget.myTest.countInts);
    }

    public int[] IntArrayField(string label, ref bool open, int[] array) {
        // Create a foldout
        open = EditorGUILayout.Foldout(open, label);
        int newSize = array.Length;

        // Show values if foldout was opened.
        if (open) {
            // Int-field to set array size
            newSize = EditorGUILayout.IntField("Size", newSize);
            newSize = newSize < 0 ? 0 : newSize;

            // Creates a spacing between the input for array-size, and the array values.
            EditorGUILayout.Space();

            // Resize if user input a new array length
            if (newSize != array.Length) {
                array = ResizeArray(array, newSize);
            }

            // Make multiple int-fields based on the length given
            for (var i = 0; i < newSize; ++i) {
                array[i] = EditorGUILayout.IntField($"Value-{i}", array[i]);
            }
        }
        return array;
    }

    private static T[] ResizeArray<T>(T[] array, int size) {
        T[] newArray = new T[size];

        for (var i = 0; i < size; i++) {
            if (i < array.Length) {
                newArray[i] = array[i];
            }
        }

        return newArray;
    }

不像 Unity 的默认设置那样美观整洁。但完成工作。

P.S:您可以在提问时 copy-paste 您的代码,而不是将其作为图片发布。很有帮助。