- Home /
How can I change all of a textures pixels to one color?
I have a painting app in which colors are painted over the top of a completely transparent, blank texture. I need to create a "clear" functionality where all the pixels in the texture are reset to a specific color (1, 1, 1, 0); which is a completely transparent white. Rather than changing out the texture each time, I would rather simply wipe all the pixels on the one texture. Here is what I've got so far but it's not working:
#pragma strict
var resetColor : Color = Color(1, 1, 1, 0);
var tex : Texture2D;
var resetColorArray = new Array ();
function Start () {
tex = renderer.material.GetTexture ("_MainTex");
resetColorArray = tex.GetPixels();
}
function Update () {
if (Input.GetKeyDown(KeyCode.Return)) {
for(var i = 0; i < resetColorArray.length; ++i)
{
resetColorArray[i] = resetColor;
}
tex.SetPixels( resetColorArray );
tex.Apply();
}
}
How can I do this?
In the start function put:
var startingX = 0; //beginning left most point of rect that will show your texture
var startingY = 0; //beginning top most point of rect that will show your texture
var pixelWidth = tex.width; //texture width
var pixelHeight = tex.height; //texture height
resetColorArray = tex.GetPixels(startingX, startingY, pixelWidth, pixelHeight);
I don't know if this works
maybe try this too
renderer.material.mainTexture = tex;
I shouldn't need to set the x,y etc when using SetPixels because as oppose to SetPixel (no "s") you only need to specify a color. I'm getting an error on line 22 about the array:
No appropriate version of 'UnityEngine.Texture2D.SetPixels' for the argument list '(Array)' was found.
But I'm not sure what's wrong with the array.
Tried your other suggestion too but it didn't solve the problem :(
Answer by Eric5h5 · Feb 09, 2014 at 11:25 AM
The resetTextureArray needs to be either a Color array, or preferably a Color32 array, which you can use with SetPixels32. Never use the Array class (for this or anything else; it's useless). Also resetTextureArray should ideally be filled once in Start, rather than every time you hit return.
Ah awesome thanks for that, that solved the problem! Cheers
This also worked for me. Thanks!
By the way, in C# it looks like this:
// New texture
texture_ = new Texture2D(x, y);
// Reset all pixels color to transparent
Color32 resetColor = new Color32(255, 255, 255, 0);
Color32[] resetColorArray = texture_.GetPixels32();
for (int i = 0; i < resetColorArray.Length; i++) {
resetColorArray[i] = resetColor;
}
texture_.SetPixels32(resetColorArray);
texture_.Apply();
Cheers