Home > Software design >  Using serializedObject from another class
Using serializedObject from another class

Time:09-22

I made a basic 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();
        }
    }

And I want to call it from the Custom editor class

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

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

But it won't work (in the DrawSerializedField function the serializedObject.FindProperty(name) return null but I do it in the custom inspector with the same name it works)

CodePudding user response:

You can pass serializedObject as a parameter to DrawSerializedField. And I don't think having EditorSerialization extend from Editor has any benefits in your case (you can't automagically access other Editor scripts' serializedObjects, as you've seen). I'd make it a static utility class if I were you:

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

CodePudding user response:

The solution is to pass the serializedObject from the first object and it didn't work for me on the start because you need to create a new instance of object.

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");
    }
}
  • You can also change the DrawSerializedField function to be static and then you won't need to create an instance of it
  • Related