Variables in editor script reset when playing

Hello everyone !
I’ve written 2 little script in order to reproduce an issue I have. I’ve done many researches about it, but I didn’t find the answers I was looking for, or maybe answers I didn’t understand…

Here is the issue : I’ve a GameObject variable named ‘gobj’ in ‘TestEditor’ that resets to its default value when I press the play button. I ask for your help because I would like to understand why. Yet, I have serialized this variable, and I have use ‘SetDirty’ my Test script (what is the use of SetDirty anyway ?). I even tried to make it public and to do some stuff with the HideFlags.DontSave. Nothing works !

However, the variables in my ‘Test’ script don’t reset, it is probably well serialized.

  • So, what difference beetween Monobehaviour inheritance and Editor inheritance justifies such an issue ?
  • I know I could put that variable in the ‘Test’ script (because srialization is OK in it), but the ‘Test’ script doesn’t really need ‘gobj’ to do its job… So what is the best way to proceed ?

Hoping I’ve well exposed my problem, I thank you for every informations you could give me :slight_smile:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    public GameObject[] gameObjects= new GameObject[15];

}

And the editor script :

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(Test))]
public class TestEditor : Editor {

    [SerializeField]
    GameObject gobj;

    
    Test myScript;

    void OnEnable()
    {
        myScript = (Test)target;
    }

    public override void OnInspectorGUI()
    {
        gobj = (GameObject)EditorGUILayout.ObjectField("gobj", gobj, typeof(GameObject), false);

        for(int i = 0; i<myScript.gameObjects.Length; i++)
        {
            myScript.gameObjects *= gobj;*

}

if (GUI.changed) { EditorUtility.SetDirty(target); }
}
}

There is a difference between MonoBehaviour and Editor scripts.

Object of MonoBehaviour can be attached to prefab and all its public fields and fields marked by SerializeFieldAttribute all will be saved into asset. And every time when Unity will load this prefab from asset, will be created object of your MonoBehaviour script and its fields will be filled by saved values.

But Editor is difference. Unity creates object of your Editor class every time when you open your MonoBehavoiur in Inspector. Editor can’t be saved into asset. When your press Play button, Unity destroys old Editor object and creates new. This way you miss your gobj in inspector. Property drawers and EditorWindows are same kind.