EditorWindow loosing reference on play how to fix

I already posted a thread of what the problem was here https://discussions.unity.com/t/684303/2

I now simplified the classes to show only the key elements of what I try to do.

The main problem lies here the _sprite reference get lost when I play the scene.

public class Child : Base {
    [SerializeField]
    private Image _image;
    [SerializeField]
    private Sprite _sprite;

    public override void DrawEditSettings() {
        GUILayout.BeginArea(new Rect(0, 20, 200, 500));
        _sprite = (Sprite)EditorGUILayout.ObjectField(_sprite, typeof(Sprite), true);
        if(_sprite != null) {
            _image.sprite = _sprite;
        }
        GUILayout.EndArea();
    }
}

The editor window also again nothing special maybe only the function DrawEditorSettings.

public class EditorWindowBase : EditorWindow {

    WindowCreater _windowCreator;

    void OnGUI() {
        if(GUILayout.Button("Create a Base and add to WindowCreater")) {
            GameObject child = PrefabUtility.InstantiatePrefab(Resources.Load(@"TEMP/Childprefab")) as GameObject;
            child.transform.parent = _windowCreator.transform;
            _windowCreator._bases.Add(child.GetComponent<Base>());
        }
        //---------- here i call the function DrawEditorSettings only for the first item in the list for the question
        if(_windowCreator._bases.Count>0) {
            _windowCreator._bases[0].DrawEditSettings();
        }
    }

    public void SetValues(WindowCreater pWindowCreator) {
        _windowCreator = pWindowCreator;
    }
}

Here the code that creates the Editor Window nothings special but still.

[CustomEditor(typeof(WindowCreater))]
public class WindowCreaterEditor : Editor {
    public override void OnInspectorGUI() {
        WindowCreater WindowCreater = (WindowCreater)target;
        if(GUILayout.Button("Create Winow")) {
            EditorWindowBase window = (EditorWindowBase)EditorWindow.GetWindow(typeof(EditorWindowBase));
            window.SetValues(WindowCreater);
            Selection.activeGameObject = WindowCreater.gameObject;
            SceneView.lastActiveSceneView.FrameSelected();
        }
    }
}
    public class WindowCreater : MonoBehaviour {
    public List<Base> _bases = new List<Base>();//public just for the question
}

And here the Base class just for measure

public abstract class Base : MonoBehaviour {
    public abstract void DrawEditSettings();
}

Thanks in advance for helping me.

it finally worked found the solution

        if(_sprite != null) {
            Undo.RecordObject(this, "Some Random text");
            _image.sprite = _sprite;
            EditorUtility.SetDirty(this);
        }
3 Likes