Search Unity

Question Values changed in variables, by a customEditor, are not saved

Discussion in 'Editor & General Support' started by ftejada, Aug 10, 2021.

  1. ftejada

    ftejada

    Joined:
    Jul 1, 2015
    Posts:
    695
    Hi everybody! Unity Version 2020.3.1f1

    I am programming a CustomInpector from which I try to change variable values from another class that does not inherit from anything and is marked as [System.Serializable]. It would be something like this:

    Code (CSharp):
    1. [System.Serializable]
    2. public class Interaction
    3. {
    4.     public int number;
    5.     //...
    6. }
    7.  
    8.  
    9. //In another script
    10. public class InteractionsObject : MonoBehaviour
    11. {
    12.     public Interaction[] interactions = new Interaction[0];
    13.     //...
    14. }
    15.  
    16. // In another script
    17. [CustomEditor(typeof(InteractionsObject))]
    18. public class InteractionsObjectEditor : Editor
    19. {
    20.     //...
    21.  
    22.     private SerializedProperty _interactions = null;
    23.  
    24.     //...
    25.  
    26.     private void OnEnable()
    27.         {
    28.         _interactions = serializedObject.FindProperty("interactions");
    29.     }
    30.  
    31.     public override void OnInspectorGUI()
    32.     {
    33.         serializedObject.Update();
    34.         EditorGUI.BeginChangeCheck();
    35.  
    36.         SerializedProperty property = _interactions.GetArrayElementAtIndex(0);
    37.         SerializedProperty p = property.FindPropertyRelative("number");
    38.    
    39.         EditorGUILayout.PropertyField(p, true);        //With this the value is changed by the Inspector, but it is reset when selecting another gameobject in the scene and reselecting this gameobject that has the script 'InteractionsObject' attached to it
    40.  
    41.         if (EditorGUI.EndChangeCheck())
    42.             {
    43.                     Undo.RecordObject(IntObj, "Undo Shape");
    44.                     serializedObject.ApplyModifiedProperties();
    45.             }
    46.     }
    47. }
    The problem is that when I change the value of any of the variables in the inspector, the new value is seen in the Inspector. But when I select another gameobject of the scene view or hierarchy and later re-select the gameobject that has the customInspector attached, I see that the values of the variables that I changed, have been reset to their original values.


    What am I doing wrong? Any idea how I can fix it?


    Greetings
    Versión de Unity 2020.3.1f1