使用另一个 class 的 serializedObject

Using serializedObject from another class

我做了一个基础的class

public class EditorSerializaion : Editor
    {
        public void DrawSerializedField(string name, string title)
        {
            SerializedProperty property;
            property = serializedObject.FindProperty(name);
            EditorGUILayout.PropertyField(property, new GUIContent(title));
            serializedObject.ApplyModifiedProperties();
        }
    }

我想从自定义编辑器中调用它class

[CustomEditor(typeof(BasicComponentScript))]
public class BaiscComponentEditor : Editor
{
    EditorSerializaion editorSerializaion;

    public override void OnInspectorGUI()
    {
        editorSerializaion.DrawSerializedField("pos", "Posotion");
    }
}

但是不行 (在 DrawSerializedField 函数中 serializedObject.FindProperty(name) return null 但我在自定义检查器中使用相同的名称进行操作)

您可以将 serializedObject 作为参数传递给 DrawSerializedField。而且我认为从 Editor 扩展 EditorSerialization 对您的情况没有任何好处(如您所见,您不能自动访问其他 Editor 脚本的 serializedObjects)。如果我是你,我会将其设为静态实用程序 class:

  • public static void DrawSerializedField(SerializedObject serializedObject, string name, string title)
  • EditorSerializaion.DrawSerializedField(serializedObject, "pos", "Position");

解决方案是从第一个对象传递 serializedObject,一开始它对我不起作用,因为您需要创建对象的新实例。

public class EditorSerializaion : Editor
{    // This has changed
    public void DrawSerializedField(SerializedObject sb,string name, string title)
    {
        SerializedProperty property;
        // This has changed
        property = sb.FindProperty(name);
        EditorGUILayout.PropertyField(property, new GUIContent(title));
        // This has changed
        sb.ApplyModifiedProperties();
    }
}

[CustomEditor(typeof(BasicComponentScript))]
public class BaiscComponentEditor : Editor
{
    EditorSerializaion editorSerializaion;

    // This is new
    private void OnEnable()
    {
        editorSerializaion = new EditorSerializaion();
    }

    public override void OnInspectorGUI()
    {    // This has changed
        editorSerializaion.DrawSerializedField(serializedObject,"pos", "Posotion");
    }
}
  • 您还可以将 DrawSerializedField 函数更改为静态函数,这样就不需要创建它的实例了