Home > database >  How do I reference the width of a sprite in C#?
How do I reference the width of a sprite in C#?

Time:11-10

I'm currently working in Unity for the first time. I'm trying to create platformer levels procedurally. I found some resources that helped me put together a pretty simple algorithm to accomplish this, but visually, it's a bit lacking. I'm using a sprite for the ground from an asset I dl'd from the asset store, and the tiles overlap, making it look rather silly. I'm trying to find out how to reference the width of the tiles so that it will draw the next one next to, rather than on top of, the previous sprite/tile. This is what my current level generator looks like:

public class LevelGenerator: MonoBehaviour
{

    [SerializeField] int width, height;
    [SerializeField] GameObject ground;
    // Start is called before the first frame update
    void Start()
    {
        Generator();
    }


    public void Generator()
    {

        for (int x = 0; x < width; x  )
        {
            for (int y = 0; y < height; y  )
            {
                Instantiate(ground, new Vector2(x, y), Quaternion.identity);
            }
    
        }

I'd like to change the x and y to x = ground.width, y = ground.height. I've googled it but haven't found any clear answer. Any direction on this would be most appreciated. Thanks all and have a good one!

CodePudding user response:

You can get the width and height of the sprite from the rect of the sprite.

width = mySprite.rect.width;
height = mySprite.rect.height;

Reference for Sprite

  • Related