场景重载后Unity引用中断

时间:2020-02-02 21:48:42

标签: c# unity3d

我在统一方面面临着一个怪异的问题,当我重新加载场景时,引用不断中断,我试图了解到底发生了什么,但是没有运气。 我做了一个脚本来复制您可以在下面找到的问题。

当我通过更改大小来编辑最后一个数据元素“列表”时,更改会反映在其他数据对象列表上,因为它们被视为引用。
enter image description here

如果我重新加载场景,则更改将不再像以前那样反映出来,这次的行为类似于副本而不是引用。
有人可以帮我弄清楚到底是怎么回事吗?
enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class test : MonoBehaviour
{

    public List<data> Data = new List<data>();
}
[System.Serializable]
public class data
{

    public List<int> list = new List<int>();
}
[CustomEditor(typeof(test))]
public class testEditor:Editor
{
    test test;
    public void OnEnable()
    {
        test = (test)target;
    }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        if (GUILayout.Button("Add"))
        {
            data data = new data();
            if (test.Data.Count >= 1) data.list = test.Data[test.Data.Count - 1].list;
            test.Data.Add(data);

            EditorUtility.SetDirty(test);
        }
        if (GUILayout.Button("Clear"))
        {
            test.Data.Clear();

            EditorUtility.SetDirty(test);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

通常:请勿直接访问和更改您的MonoBehaviour实例的值!

如您所述,您将必须处理各种脏污标记并保存自己。在编辑器中重新打开场景时,您会遇到以下错误:未正确标记某些内容,因此未将其与场景一起保存。


宁愿经过SerializedProperty来处理所有标记变脏和保存,尤其是自动撤消/重做等操作:

[CustomEditor(typeof(test))]
public class testEditor : Editor
{
    private SerializedProperty Data;

    public void OnEnable()
    {
        Data = serializedObject.FindProperty(nameof(test.Data));
    }

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        // load all current values of the properties in test into the SerializedProperty "clones"
        serializedObject.Update();

        if (GUILayout.Button("Add"))
        {
            // this simply adds a new entry to the list
            // since the data and list are both serializable this already initializes them with values
            Data.arraySize++;


            // Actually the entire following block is redundant 
            // by using Data.arraySize++; the new added entry automatically 
            // is a full copy of the entry before!
            // I just decided to add it as example how you would access further nested SerializedProperties

            //// if there was an element before now there are two
            //if (Data.arraySize >= 2)
            //{
            //    // get the last added element
            //    var lastElement = Data.GetArrayElementAtIndex(Data.arraySize - 1);
            //    var beforeElement = Data.GetArrayElementAtIndex(Data.arraySize - 2);

            //    // deep clone the list
            //    var lastElementList = lastElement.FindPropertyRelative(nameof(data.list));
            //    var beforeElementList = beforeElement.FindPropertyRelative(nameof(data.list));

            //    lastElementList.arraySize = beforeElementList.arraySize;
            //    for (var i = 0; i < lastElementList.arraySize; i++)
            //    {
            //        lastElementList.GetArrayElementAtIndex(i).intValue = beforeElementList.GetArrayElementAtIndex(i).intValue;
            //    }
            //}
        }

        if (GUILayout.Button("Clear"))
        {
            Data.arraySize = 0;
        }

        // write back the values of the SerializedProperty "clones" into the real properties of test
        serializedObject.ApplyModifiedProperties();
    }
}

这现在可以处理所有标记变脏,正确保存场景,自动撤消/重做等操作,您不必再担心了。


然后是一些“专业”提示:使用ReorderableList!设置起来似乎有些棘手,但功能却非常强大:顾名思义,它可以让您简单地通过在Inspector中拖放来重新排列元素,还可以从中间删除项目,而这在菜单中是不可能的。普通列表抽屉。这将完全取代您的AddClear按钮:

using UnityEditor;
using UnityEditorInternal;

[CustomEditor(typeof(test))]
public class testEditor : Editor
{
    private SerializedProperty Data;
    private ReorderableList dataList;

    public void OnEnable()
    {
        Data = serializedObject.FindProperty(nameof(test.Data));

        //                                 should the list
        //                                                     | be reorderable by drag&drop of the entries?
        //                                                     |     | display a header for the list?
        //                                                     |     |     | have an Add button?
        //                                                     |     |     |     | have a Remove button?
        //                                                     v     v     v     v
        dataList = new ReorderableList(serializedObject, Data, true, true, true, true)
        {
            // what shall be displayed as header
            drawHeaderCallback = rect => EditorGUI.LabelField(rect, Data.displayName),

            elementHeightCallback = index =>
            {
                var element = Data.GetArrayElementAtIndex(index);
                var elementList = element.FindPropertyRelative(nameof(data.list));
                return EditorGUIUtility.singleLineHeight * (elementList.isExpanded ? elementList.arraySize + 4 : 3);
            },

            drawElementCallback = (rect, index, isFocused, isActive) =>
            {
                var element = Data.GetArrayElementAtIndex(index);

                EditorGUI.LabelField(new Rect(rect.x,rect.y,rect.width,EditorGUIUtility.singleLineHeight), element.displayName);
                // in order to print the list in the next line
                rect.y += EditorGUIUtility.singleLineHeight;

                var elementList = element.FindPropertyRelative(nameof(data.list));
                EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width,  EditorGUIUtility.singleLineHeight * (elementList.isExpanded ? elementList.arraySize + 1 : 1)), elementList, true);
            }
        };
    }

    public override void OnInspectorGUI()
    {
        // load all current values of the properties in test into the SerializedProperty "clones"
        serializedObject.Update();

        dataList.DoLayoutList();

        // write back the values of the SerializedProperty "clones" into the real properties of test
        serializedObject.ApplyModifiedProperties();
    }
}

enter image description here


注意:如果不是这种情况,请执行以下操作: testEditor部分应

  • 可以放置在名为Editor的文件夹中的其他脚本中
  • ,否则您应该将与UnityEditor名称空间相关的所有内容包装在预处理器中,例如

    #if UNITY_EDITOR
    using UnityEditor;
    using UnityEditorInternal;
    #endif
    
    ...
    
    #if UNITY_EDITOR
    [CustomEditor(typeof(test))]
    public class testEditor : Editor
    {
        ...
    }
    #endif
    

否则,在构建应用程序时会出错,因为UnityEditor名称空间是在构建中删除的,并且仅存在于Unity Editor本身内。