Creating a sprite from a Texture2D
Hey,
I've been working on this project where I'm creating a canvas on which a user can draw pixel-style character, which would then be converted into a sprite to be displayed in the game. The drawing is working (likely not the best solution, but hey, at least it works) but I'm having issues with converting the Texture2D to a sprite.
Here's what I've got to create the sprite:
private Sprite DrawSprite()
{
int drawIndex = 0; //to keep track of which pixel the loop is on; pixels are stored in a Pixel[] of pixels, see code block below
Texture2D texture = new Texture2D(meshWidth, meshHeight, TextureFormat.ARGB32, false);
for (int i = 0; i < meshWidth; i++)
{
for (int j = 0; j < meshHeight; j++)
{
//get the next pixel from the array
Pixel pixel = pixels[drawIndex];
//assign the pixel's values to be added as a pixel to the Texture2D
texture.SetPixel(pixel.xIndex, pixel.yIndex, pixel.color);
index++;
}
}
texture.Apply();
//create the sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 10f);
return sprite;
}
I'm using a "Pixel" class to keep track of each individual pixel's x-index and y-index on the texture as well as color.
public class Pixel
{
public int xIndex { get; set; }
public int yIndex { get; set; }
public Color color { get; set; }
public Pixel(int x, int y, Color c)
{
this.xIndex = x;
this.yIndex = y;
this.color = c;
}
}
So basically, I'm changing the color values of the pixels elsewhere while drawing (which works), but when I'm applying that data to the Texture2D and converting that to a Sprite, it gives out this result, no matter what the input supposedly was:
I've checked that the indexes and color values on the Pixel-class instances are correct, yet they don't seem to get applied correctly to the correct places on the sprite. Any ideas on why this might be happening?
EDIT: The grey areas on the sprite are clear on a grey background, because the default pixel color value is set to Color.clear. The problem is that the black ones (currently working in b&w) aren't getting to where they should be.
Your answer
![](https://koobas.hobune.stream/wayback/20220613004031im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
ScreenCapture.CaptureScreenshotAsTexture() is making a milky white tinted screenshot. 1 Answer
Is it possible to create a texture that hides a specific texture? 0 Answers
SetPixel and cloning sprite.texture 0 Answers
Unity display image from assets folder 0 Answers
Switch Texture Type To Sprite. 0 Answers