Dynamic Texture2D in UnityUI

This is in relation to an earlier post (http://forum.unity3d.com/viewtopic.php?t=30090).

I got some great tips on how to do irregular shaped health bars using GUITexture. Before I decided to go that route, I came on an idea that would let me accomplish the task in UnityUI using GUI.DrawTexture calls. However, I’ve run into a problem that I’m hoping is obvious to someone.

Here’s my code (this is just a trial run to get the mask to be copied to a target texture and then displayed. Further work will have the target texture have different colors and such).

void SetHealthBarTex()
{
    Texture2D playerHealthMaskTexture;
    Color[] playerHealthColors;
    Texture2D playerHealthTexture;

        playerHealthMaskTexture = (Texture2D)Resources.Load("UI/Brawler/PlayerBarHealthMask");
        playerHealthTexture = new Texture2D(playerHealthMaskTexture.width, playerHealthMaskTexture.height, TextureFormat.ARGB32, true);
        playerHealthColors = playerHealthMaskTexture.GetPixels(0);
playerHealthTexture.SetPixels(playerHealthColors);
        playerHealthTexture.Apply();
}


    public override void OnGUI()
    {
GUI.DrawTexture(new Rect(0, 0, 300, 120), playerHealthTexture);
    }

What happens when I run this is that I get no image drawn. If I attempt to access properties of playerHealthTexture, I get this message:

MissingReferenceException: The object of type ‘Texture2D’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

This is mysterious to me. If I replace the playerHealthTexture with the playerHealthMaskTexture (only difference being the latter is loaded via Resources.Load, whereas the former is created dynamically in the initialization), the image will show up as I expect without the error message.

Further, I found that i could successfully get this to work by creating the texture inside the draw call:

void SetHealthBarTex()
{
    Texture2D playerHealthMaskTexture;
    Color[] playerHealthColors;

        playerHealthMaskTexture = (Texture2D)Resources.Load("UI/Brawler/PlayerBarHealthMask");
        playerHealthColors = playerHealthMaskTexture.GetPixels(0);
}


    public override void OnGUI()
    {
    Texture2D playerHealthTexture;
        playerHealthTexture = new Texture2D(playerHealthMaskTexture.width, playerHealthMaskTexture.height, TextureFormat.ARGB32, true);
playerHealthTexture.SetPixels(playerHealthColors);
        playerHealthTexture.Apply();
GUI.DrawTexture(new Rect(0, 0, 300, 120), playerHealthTexture);
    }

This code works beautifully exactly as I’d expect… for twenty seconds or so until Unity crashes with a message in the debug log that it’s out of memory. Clearly, creating a texture2d every frame is, as expected, a bad idea. Yet it does show that it can work.

So I’m confused as to what differences occur between “Texture2D t = new Texture2D(w,h)” and “Resources.Load(“ui/texture”)” that make one stick around and the other disappear.

If I can make this approach work of dynamically creating and modifying a texture2d based on a provided masked texture and some variables (how much power a player has), then I can accomplish what i need within UnityUI fairly efficiently (I’d only need to modify the dynamic texture when a health event occurs, so I wouldn’t be pixel tweaking every frame).

Thanks for any insight.

Sorry for the short reply, I have to “hit and run”, but you do NOT want to create new Textures each frame, as you found out. :wink:

Textures (including Texture2Ds) must be explicitly destroyed or they stick around in memory, generally. Hence your out of memory crash.

You want to create the texture once, and mess with its pixels how you need to every frame.

Also note that with your first code example, the playerHealthTexture is declared within a method, so it will have its scope limited to that method. That will be the cause of your null ref issues and so on.

I haven’t had a chance to read your post or code in detail, but hopefully that will help somewhat.

-Jeremy

Hey there. Thanks for the reply. Yeah, I pretty much only did the “Create a texture every frame” just to test that it even worked (which it did for twenty seconds… sadly, our game is required to run a bit longer than that. :wink: )

Thanks for noticing the local declaration of the textures. I actually had declared them at the class level (which stays around for the length of the application), but had copied them into the example method without realizing it in a spot that was local to the body of the function; yes, you’re right, declaring locally would have explained the null reference declarations.

Even when playerHealthTexture is declared outside the scope of the method, the null reference error continues. Very odd. Odder still that one texture (playerHealthTextureMask) works as expected since it’s being loaded via Resources.Load, where the playerHealthTexture, defined and declared identically to the playerHealthTextureMask, doesn’t remain past the scope of the function.

Either way, thanks for your insights!

Oh, and here’s a less terse code sample:

public class BrawlerPlayerBarTemp : MonoBehavior
{

    // Define all Canvases and GUIX controls here
    Texture2D playerHealthMaskTexture;
    Color[] playerHealthColors;
    Texture2D playerHealthTexture;

    public BrawlerPlayerBarTemp() 
    {
        // Set up the texture that will be used for the power bar (need to custom mask it). 
        playerHealthMaskTexture = (Texture2D)Resources.Load("UI/Brawler/PlayerBarHealthMask");
        playerHealthTexture = new Texture2D(playerHealthMaskTexture.width, playerHealthMaskTexture.height, TextureFormat.ARGB32, true);

        int width = playerHealthMaskTexture.width;
        int height = playerHealthMaskTexture.height;

        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                int bitIdx = i + j * width;
                if ((playerHealthColors[bitIdx]).a > 0)
                {
                    playerHealthColors[bitIdx] = new Color(1f, 0f, 0f, 1f);
                                    }
                else
                {
                    playerHealthColors[bitIdx] = new Color(0f, 0f, 0f, 0f);
                                    }
            }
        }
    }

    public void OnGUI    {
playerHealthTexture.SetPixels(playerHealthColors);
        playerHealthTexture.Apply();
GUI.DrawTexture(new Rect(0, 0, 300, 120), playerHealthTexture); 
    }

OnGUI needs () after it (probably just a copy-paste error or something), and you never want to use a standard constructor for a MonoBehaviour subclass. This constructor can be run at any time (including in the editor), and this can cause lots of issues. Use Start or Awake instead.

The constructor use may be what’s causing issues for you.

-Jeremy

Oh, I forgot to mention, remember that OnGUI is called twice per update, so the Apply and SetPixels calls are being run twice. You’ll want to move them out of there.

-Jeremy