Home > Back-end >  How do I detect the transparent part of a sprite in unity
How do I detect the transparent part of a sprite in unity

Time:07-11

I have a sprite that is partly transparent.

enter image description here

My aim is to fill the image with some square prefabs.

I have written this code which works fine.

while (newY < endVertical)
{
        while (newX < endHorizontal)
        {
                Instantiate(filler, new Vector3(newX, newY, 0), Quaternion.identity);
                newX  = fillerWidth   0.1f;
        }

        newY  = fillerHeight   0.1f;
        newX = startHorizontal;
}

The result is

enter image description here

My goal is however to only draw the white prefabs only on the visible part of the image. I want my result to be something like this

enter image description here

To achieve this I have added a little change to check the color at each pixel and only instantiate the prefab if the color is not clear.

 var colorSelected = player.GetComponent<SpriteRenderer>().sprite.texture.GetPixel((int) newX, (int) newY);
                if (colorSelected != Color.clear)
                {
                    Instantiate(filler, new Vector3(newX, newY, 0), Quaternion.identity);
                }

This, however does not work.

I have also tried this enter image description here

CodePudding user response:

You can read pixels of texture via Texture2D.GetPixel and think texture as sets of chunks. Set the chunk as the same size as square and if there are any colored pixel in the chunk, render the square at the position.

  • Related