1
\$\begingroup\$

I am trying to programmatically make an Image to cover the entire screen. I create the Texture2D, then create a Sprite from the Texture2D, then apply the Sprite to my Image. This works, but it is slow.

I suspect the issue is that I am setting each pixel individually for my Texture2D:

private static Texture2D CreateSolidTexture2D(Color color)
{
    var texture = new Texture2D(Screen.width, Screen.height);
    for (int y = 0; y < texture.height; y++)
    {
        for (int x = 0; x < texture.width; x++)
        {
            texture.SetPixel(x, y, color);
        }
    }
    texture.Apply();
    return texture;
}

I have tried creating the Texture2D by resizing a Texture2D of a single pixel, but the color comes out as a translucent white, instead of the color passed:

private static Texture2D CreateSolidTexture2D(Color color)
{
    var texture = new Texture2D(1, 1);
    texture.SetPixel(0, 0, color);
    texture.Resize(Screen.width, Screen.height);
    texture.Apply();
    return texture;
}

Why doesn't my second approach work? How can I efficiently create a screen-sized Texture2D of a solid color?

\$\endgroup\$
2
\$\begingroup\$

Instead of texture.SetPixel, use texture.SetPixels

var texture = new Texture2D(Screen.width, Screen.height);
Color[] pixels = Enumerable.Repeat(color, Screen.width * Screen.height).ToArray();
texture.SetPixels(pixels);
texture.Apply();
return texture;

Using texture.LoadRawTextureData might be even faster, but this requires that you know more about your texture format.

Alternatively you could use the hard-coded Texture2D.whiteTexture, stretch it to the size of the screen and set the color through the shader (this is what I would really recommend you to do if you plan to show a lot of different colors in quick succession).

\$\endgroup\$
  • \$\begingroup\$ I tried Texture2D.blackTexture and resized it, but I had the same result of the translucent white color. The Linq option presented is much faster though. Thank you! \$\endgroup\$ – Evorlor May 16 '17 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.