- Home /
Sprite creation problem
Hi: I was trying to create a simple image in runtime, I create a texture, and then use the Sprite.Create to create the sprite, but when I play the game, the texture is ok but the sprite is transparent, it has the pivot in the center and the correct dimensions, but the image isn't here. Here´s, the code:
private Texture2D drawMap (int dimX, int dimY, string mapa)
{
Texture2D aux = new Texture2D (dimX, dimY);
aux.filterMode = FilterMode.Point;
for (int i = 0; i < dimX; i++)
{
for (int j = 0; j < dimY; j++)
{
int cuadro = (int)(mapa [i * dimY + j] - '0');
if (cuadro >= 4 && cuadro <= 8)
aux.SetPixel (i, j, this.colorPared);
else //Error = pared
aux.SetPixel (i, j, this.colorSuelo);
}
}
aux.Apply ();
return aux;
}
public void changeImage (int dimX, int dimY, string mapa)
{
Texture2D tex = this.drawMap (dimX, dimY, mapa);
imagen.sprite = Sprite.Create (tex, new Rect (0, 0, tex.width, tex.height), new Vector2 (0.5f, 0.5f));
//imagen is a Image variable
}
(Sorry for some variable names in spanish) I tried everything, but nothing has work, any idea? Thanks
Answer by TriBackBill · Jun 29, 2020 at 03:25 PM
I was experiencing a similar problem but managed to fix it by applying the texture. I'm aware of the age of the post, however there don't seem to be many answers for this kind of issue.
Here's my code that works:
public static Texture2D GenTexture()
{
Texture2D tex = new Texture2D(32, 32);
for (int x = 0; x < 32; x++)
{
for (int y = 0; y < 32; y++)
{
tex.SetPixel(x, y, new Color(x/32, y/32, 1, 1));
}
}
tex.Apply();
tex.filterMode = FilterMode.Point;
return tex;
}
Your answer
Follow this Question
Related Questions
Help with changing spririterenderer's sprite 2 Answers
Create colored rectangle at runtime 1 Answer
How expensive is scaling in 2D unity? Is it better to pre-scale? 1 Answer
How to show sprite changes made in a Graphics Editor during runtime in Unity Editor 0 Answers
Execute editor window scripts when project errors are present 0 Answers