- Home /
Drawing onto the Texture2D of a sprite
I would like to make a drawing feature for something i'm doing and I need to be able to draw onto a Texture2D via mouse input. I was curious if there was a way to easily change the Texture2D?
Answer by monoclesociety · Jun 20, 2014 at 02:25 AM
So I did eventually figure this out, below is a small script that I put in my scene that takes a reference to an empty spriteRenderer. This code creates a new sprite out of a new Texture2d, and fills in a quarter of it with red.
public class SpriteDrawing : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
private Texture2D spriteTexture2D;
void Start ()
{
this.spriteTexture2D = new Texture2D(512,512);
Rect r = new Rect(0,0,512,512);
Vector2 pivot = new Vector2(0,0);
Sprite sprite = Sprite.Create(this.spriteTexture2D,r,pivot);
this.spriteRenderer.sprite = sprite;
StartCoroutine("delayedDraw");
}
IEnumerator delayedDraw()
{
yield return new WaitForSeconds(.5f);
for(int x = 0; x <= 256; x++)
{
for(int y = 0; y <= 256; y++)
{
this.spriteTexture2D.SetPixel(x,y,Color.red);
}
}
this.spriteTexture2D.Apply();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613145611im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can't create a 2D sprite with Sprite.Create when creating texture in code 1 Answer
Is it impossible to swap the Texture2D of a Sprite Renderer at runtime? 1 Answer
Strange edge on texture after hiding pixels 3 Answers
How to Address Texture2D Elements from a Sprite with Sprite Mode: Multiple, in Code? 1 Answer