Reputation:
I have a 32x32 sprite that I am trying to access the pixel data of and modify.
To do this I am simply taking the sprite's texture, creating a new texture based on the old and then changing the pixel values of the new texture. I then create a new sprite with the modified texture and change the SpriteRenderer's sprite parameter to the new sprite.
However, when I actually run my script what I get is a huge grey square, easily 10x the size of the original 32x32 sprite. I'm very new to unity so I'm not sure why this is happening. Any insight would be great.
private Sprite sprite;
private Texture2D texture;
// Use this for initialization
void Start ()
{
sprite = this.gameObject.GetComponent<SpriteRenderer>().sprite;
texture = sprite.texture;
Texture2D newTexture = modifyTexture(texture);
SpriteRenderer sr = this.gameObject.GetComponent<SpriteRenderer>();
sr.sprite = Sprite.Create(newTexture, new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0, 0), 10);
}
public Texture2D modifyTexture(Texture2D baseTexture)
{
Texture2D newTexture = new Texture2D(baseTexture.width, baseTexture.height);
int x = 0;
while(x < newTexture.width)
{
int y = 0;
while(y < newTexture.height)
{
Color currentPixel = baseTexture.GetPixel(x,y);
Color modifiedPixel = currentPixel;
modifiedPixel.r = (float)(modifiedPixel.r + 0.10);
modifiedPixel.b = (float)(modifiedPixel.b + 0.10);
modifiedPixel.g = (float)(0.10);
newTexture.SetPixel(x, y, modifiedPixel);
y++;
}
x++;
}
Debug.Log(newTexture.GetPixel(5, 5).ToString());
return newTexture;
}
Upvotes: 1
Views: 1110
Reputation: 125275
After modifying pixels of a Texture, you must call the Apply
function upload the modified pixels to the graphics card.
public Texture2D modifyTexture(Texture2D baseTexture)
{
Texture2D newTexture = new Texture2D(baseTexture.width, baseTexture.height);
int x = 0;
while (x < newTexture.width)
{
int y = 0;
while (y < newTexture.height)
{
Color currentPixel = baseTexture.GetPixel(x, y);
Color modifiedPixel = currentPixel;
modifiedPixel.r = (float)(modifiedPixel.r + 0.10);
modifiedPixel.b = (float)(modifiedPixel.b + 0.10);
modifiedPixel.g = (float)(0.10);
newTexture.SetPixel(x, y, modifiedPixel);
y++;
}
x++;
}
//Upload changes to Graphics graphics card
newTexture.Apply();
Debug.Log(newTexture.GetPixel(5, 5).ToString());
return newTexture;
}
Upvotes: 2