Unity C#:修改抽象元素列表中的参数



我有一个类,其中包含一个类列表,该列表派生自一个抽象的超类。

[System.Serializable]
public class ClassWithList: MonoBehaviour
{
    [SerializeField]
    private List<Element> elements;
    public List<Element> Elements
    {
        get
        {
            if (elements == null)
                elements= new List<Element>();
            return elements;
        }
    }
}
[System.Serializable]
public abstract class Element: MonoBehaviour
{
    [SerializeField]
    protected bool isClickedInList;
    public bool IsClickedInList
    {
        get { return isClickedInList; }
        set { isClickedInList = value;  }
    }
}

我使用带有可重新排序列表的自定义编辑器来修改元素实体的值ClassWithList

[CustomEditor(typeof(ClassWithList))]
public class Editor_ClassWithList : Editor
{
    private ReorderableList elementList;
    void OnEnable()
    {
        if (elementList== null)
            elementList=
                new ReorderableList(
                    serializedObject, serializedObject.FindProperty("elements"),
                    true, true, true, true);
        elementList.drawElementCallback += DrawElement;
    }
    private void OnDisable() { elementList.drawElementCallback -= DrawElement; }
    private void DrawElement(Rect r, int i, bool active, bool focused)
    {
        Element e = elementList.serializedProperty.GetArrayElementAtIndex(i).objectReferenceValue as Element;
        e.IsClickedInList = EditorGUI.Toggle(new Rect(r.x, r.y, r.width, r.height - 1), e.IsClickedInList);
    }
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        elementList.DoLayoutList();
        serializedObject.ApplyModifiedProperties();
    }
}

列表正确显示并显示所有元素。单击切换按钮会导致正确更改元素isClickedInList值。但是一旦我按下"播放",这个值就会被覆盖,就好像它不会被序列化一样。

有什么想法出了问题吗?使用 serializedObject.FindProperty("elements") 可能会导致此问题吗?

使用提供的示例进行进一步测试并与我的代码进行比较显示,问题是游戏对象是预制件。不知何故,这会导致使用序列化属性的非保存行为,尽管我无法重现该错误。

最新更新