Keep references in EditorWindow after scripts recompiling

Hello,

I’m struggling with this editor scripting issue…

My goal is to create a Texture2D inside the Editor Window and keep its reference alive after recompiling.

If I use a classic variable inside the window, everything works fine.

Editor Window 1

using UnityEngine;
using UnityEditor;

public class RecompileTest1 : EditorWindow
{
    public Texture2D tex;
   
    [MenuItem("Window/Recompile Test 1")]
    static void Init()
    {
        RecompileTest1 recompileTest = (RecompileTest1) GetWindow(typeof(RecompileTest1));
        recompileTest.Show();
    }

    private void Awake()
    {
        tex = Texture2D.whiteTexture;
    }

    void OnGUI()
    {
        if (tex == null)
        {
            GUILayout.Label("Texture is null", EditorStyles.boldLabel);
        }
        else
        {
            GUILayout.Label("Texture is NOT null", EditorStyles.boldLabel);
            GUI.DrawTexture(new Rect(50, 50, 100, 100), tex, ScaleMode.ScaleToFit);
        }

    }
}

But if this texture is created inside an instance which is referenced in the window, after recompiling the instance is gone and the texture too…

Editor Window 2

using UnityEngine;
using UnityEditor;

public class TextureContainer
{
    public Texture2D tex;
}

public class RecompileTest2 : EditorWindow
{
    private TextureContainer container;
    
    [MenuItem("Window/Recompile Test 2")]
    static void Init()
    {
        RecompileTest2 recompileTest2 = (RecompileTest2) GetWindow(typeof(RecompileTest2));
        recompileTest2.Show();
    }

    private void Awake()
    {
        container = new TextureContainer();  //this instance will be NULL after recompiling scripts
        container.tex = Texture2D.whiteTexture; //tex is now inside the container
    }

    void OnGUI()
    {
        if (container == null)
        {
            GUILayout.Label("Container is null, we can't access the texture!", EditorStyles.boldLabel);
        }
        else
        {
            GUILayout.Label("Container is NOT null, and we can access the texture", EditorStyles.boldLabel);
            GUI.DrawTexture(new Rect(50, 50, 100, 100), container.tex, ScaleMode.ScaleToFit);
        }

    }
}

Is there something I can do to keep these references?

Thank you,

Francesco

Marking TextureContainer as [Serializable] would be a good start, as well as marking the private field with [SerializeField]

1 Like

Thanks man, your solution works. Fast as hell!!!

One note is that the inner fields must be non-static, otherwise they are destroyed.

Well yeah, static fields don’t belong to any object, so they will be lost.

1 Like