Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question References being deleted on stage change in latest releases

Discussion in 'Scripting' started by JoePatrick, Apr 1, 2024.

  1. JoePatrick


    Nov 3, 2013
    Hi so I have some code that is essentially:

    • Setup a new stage/preview scene
    • Create new Texture2D(width, height)
    • Render scene to Texture2D
    • Close and delete the scene/stage
    • Return the Texture2D
    This used to work fine, but in 2023.3.0b10 and 6000.0.0b13 this doesn't work anymore.
    When I call StageUtility.GoToMainStage(), the Texture2D is deleted and so when I return it and then try to access it I just get an error that it has been deleted.

    How can I move the Texture2D out of the preview scene/stage without it being deleted.

    Here is my full function code
    Code (CSharp):
    1.         public static Texture2D RenderIcon(Icon icon, int width = 128, int height = 128)
    2.         {
    3.             //---Fix width/height---//
    4.             width = Mathf.Clamp(width, 8, 2048);
    5.             height = Mathf.Clamp(height, 8, 2048);
    7.             //---Create stage and scene---//
    8.             var scene = EditorSceneManager.NewPreviewScene();
    9.             if (scene == null)
    10.             {
    11.                 Debug.LogError("Error creating RapidIcon preview scene");
    12.                 return Utils.CreateColourTexture(width, height, Color.clear);
    13.             }
    15.             var stage = ScriptableObject.CreateInstance<RapidIconStage>();
    16.             if (stage == null)
    17.             {
    18.                 Debug.LogError("Error creating RapidIcon stage");
    19.                 return Utils.CreateColourTexture(width, height, Color.clear);
    20.             }
    22.             stage.SetScene(scene);
    24.             //---Go to stage---//
    25.             StageUtility.GoToStage(stage, true);
    27.             //---Setup scene---//
    28.             stage.SetupScene(icon);
    30.             //and render icon---//
    31.             Texture2D render = stage.RenderIcon(width, height);
    33.             //---Apply post-processing shaders---//
    34.             Texture2D img = CreateColourTexture(width, height, Color.clear);
    36.             foreach (Material m in icon.iconSettings.postProcessingMaterials)
    37.             {
    38.                 if (icon.iconSettings.materialToggles != null)
    39.                 {
    40.                     if (icon.iconSettings.materialToggles[m])
    41.                     {
    42.                         var rtd = new RenderTextureDescriptor(img.width, img.height) { depthBufferBits = 24, msaaSamples = 8, useMipMap = false, sRGB = true };
    43.                         var rt = new RenderTexture(rtd);
    45.                         if (m == null)
    46.                             continue;
    48.                         if ( == "RapidIcon/ObjectRender")
    49.                             m.SetTexture("_Render", render);
    51.                         Graphics.Blit(img, rt, m);
    53.                = rt;
    54.                         img = new Texture2D(img.width, img.height);
    55.                         img.ReadPixels(new Rect(0, 0, img.width, img.height), 0, 0);
    56.                         img.Apply();
    57.                = null;
    58.                         rt.Release();
    59.                     }
    60.                 }
    61.             }
    63.             //---Apply filter mode---//
    64.             img.filterMode = icon.iconSettings.filterMode;
    66.             //---Cleanup stage and scene---//
    67.             //  !! img is valid here !!
    68.             StageUtility.GoToMainStage();
    69.             // !! img is null here !!
    70.             EditorSceneManager.ClosePreviewScene(scene);
    71.             ScriptableObject.DestroyImmediate(stage);
    73.             return img;
    74.         }
  2. CodeSmile


    Apr 10, 2014
    There's always the option to create a texture asset and delete it afterwards.

    But since your method is holding a reference to the texture, it shouldn't be null'ed no matter what. How did you do the null check? Did you try ReferenceEquals check? I can only imagine that the underlying C++ texture may have been disposed.

    Maybe it has something to do that you're creating new textures within the loop, replacing the previous img:
    img = new Texture2D(img.width, img.height);

    Or CreateColourTexture returns a shared texture that gets disposed. What does it do?

    Other than that I'm stumped why img would be null. It's clearly in scope.
    But I'm also stumped as to what that code does. Could you elaborate?

    Btw, I suggest moving the m==null check as the first line of the foreach, because none of the code up to where you do the null check needed to be run if m were null.
  3. JoePatrick


    Nov 3, 2013
    I was just doing Debug.Log(img) to see when it was becoming null.
    Debug.Log(Texture2D.ReferenceEquals(img, null)); returns false both before and after GoToMainStage.

    I tried removing the "new Texture2D" from the loop, no difference.
    CreateColourTexture just creates a new texture2D of a width and height, and assigns all pixels the given colour.
    Code (CSharp):
    1.         public static Texture2D CreateColourTexture(int width, int height, Color c)
    2.         {
    3.             //---Create new texture---//
    4.             Texture2D tex = new Texture2D(width, height);
    6.             //---Set pixel colours---//
    7.             Color[] pixels = Enumerable.Repeat(c, width * height).ToArray();
    8.             tex.SetPixels(pixels);
    10.             //---Apply changes and set filter mode---//
    11.             tex.Apply();
    12.             tex.filterMode = FilterMode.Point;
    14.             return tex;
    15.         }
    This code creates a new preview scene, adds some objects and then renders the camera to a Texture2D, which I want to return.
    Seems to be some kind of automatic disposal as the Texture2D is getting created in the preview scene and then being deleted when the scene is closed. For example, if I create the Texture2D (e.g. CreateColourTexture) before the call to "StageUtility.GoToStage", then the error comes up when I try and access the Texture2D from witin the preview scene, as I guesss in that scenario it is being created in the main scene and then deleted as the preview scene becomes active.
  4. CodeSmile


    Apr 10, 2014
    It shouldn't matter where the texture is created. The texture has no relation to the scene at all unless you assign it to a scene object. But it may still be managed differently than other assets since it's uploaded to the GPU.

    What happens if you only create a basic new texture in the preview stage, and then leave the stage. Is this texture also null'ed?

    Another way you can keep the texture alive is to return the pixel data rather than the textures, so you can create a new texture after the method returns.
  5. JoePatrick


    Nov 3, 2013
    Yeah it happens even with a simple scenario like this
    Code (CSharp):
    1.             Texture2D textest = CreateColourTexture(1, 1, Color.clear);
    2.             Debug.Log(textest); //prints texture
    3.             StageUtility.GoToMainStage();
    4.             Debug.Log(textest); //prints null
    I think caching the pixel data and rebuilding the texture after changing scenes might be the best option,
  6. CodeSmile


    Apr 10, 2014
    Hmmm you may want to send a bug report with this simple test case, particularly since this behaviour has changed in Unity 6 beta.
  7. Bunny83


    Oct 18, 2010
    Try using DontDestroyOnLoad on the texture object before you load the new scene. Note that currently you're leaking all those textures that you create in your loop as you just throw away the references. Textures are UnityEngine.Object derived and as such are not directly garbage collected as they are tracked objects. However when UnloadUnusedAssets is called (which happens automatically during a scene load) any assets that aren't referenced anymore would be destroyed.

    You should be more careful about your object creation and also explicitly clean up the instances you create. You should not rely on UnloadUnusedAssets.