Search Unity

Custom Editor: Field reverts after saving and closing/reloading scene

Discussion in 'Scripting' started by SentientSkull, Dec 3, 2020.

  1. SentientSkull

    SentientSkull

    Joined:
    Apr 26, 2013
    Posts:
    75
    I have an editor script that calls an external method in OnInspectorGUI() to set a serialized field.

    I use 'Undo.RecordObject' in the external method. But when I save, close and reload the scene, the field hasn't saved the changes (the field is a GameObject reference). What do I need to do get this to save properly?

    Code (CSharp):
    1. public override void OnInspectorGUI()
    2. {
    3.    serializedObject.Update();
    4.  
    5.    UniqueObjectId uniqueObjectId = target as UniqueObjectId;
    6.  
    7.    EditorGUILayout.PropertyField(idString);
    8.    EditorGUILayout.PropertyField(objectListManager);
    9.  
    10.    GUILayout.BeginHorizontal();
    11.    if (GUILayout.Button("Get ObjectListManager"))
    12.    {
    13.        uniqueObjectId.GetObjectListManager();
    14.    }
    15.    if (GUILayout.Button("Generate ID String"))
    16.    {
    17.        uniqueObjectId.GenerateIfEmpty();
    18.    }
    19.     GUILayout.EndHorizontal();
    20.  
    21.    serializedObject.ApplyModifiedProperties();
    22. }
    Code (CSharp):
    1. public virtual void GetObjectListManager()
    2. {
    3.     var managers = GameObject.FindGameObjectWithTag("Managers");
    4.     if (managers)
    5.     {
    6.         if (objectListType == ObjectListType.Scene)
    7.         {
    8. #if UNITY_EDITOR
    9.             Undo.RecordObject(this, "Set Object List Manager");
    10. #endif
    11.             objectListManager = managers.GetComponentInChildren<SceneObjectListManager>();
    12.         }
    13.         else if (objectListType == ObjectListType.Dynamic)
    14.         {
    15. #if UNITY_EDITOR
    16.             Undo.RecordObject(this, "Set Object List Manager");
    17. #endif
    18.             objectListManager = managers.GetComponentInChildren<DynamicObjectListManager>();
    19.         }
    20.     }
    21. }
     
  2. MrPaparoz

    MrPaparoz

    Joined:
    Apr 14, 2018
    Posts:
    157
    This might be the solution, I'm not sure.
    Code (CSharp):
    1.  
    2. public override void OnInspectorGUI(){
    3.    EditorGUI.BeginChangeCheck();
    4.    //your functions
    5.    if(EditorGUI.EndChangeCheck()){
    6.         EditorUtility.SetDirty(this);
    7.    }
    8. }
     
  3. SentientSkull

    SentientSkull

    Joined:
    Apr 26, 2013
    Posts:
    75
    I changed 'GetObjectListManager' to a function and changed the button code to set the 'objectReferenceValue' of the field to take its return value and it seems to work now.

    Code (CSharp):
    1. if (GUILayout.Button("Get ObjectListManager"))
    2. {
    3.     objectListManager.objectReferenceValue = uniqueObjectId.GetObjectListManager();
    4. }