Search code examples
unity-game-enginespritegame-engine

Getting the width of a sprite


I am trying to create a row out of some square sprites I have. So to get the width of these sprites i am using

tileWidth = (int)tileSet[0].renderer.bounds.size.x;

And then to form the row i am uisng

for(int i = 0; i < tileSet.Length ; i++){
    if((i+1)*tileWidth<screenWidth){
        tileSet[i].transform.position = new Vector3(i*tileWidth,0,0);
    }
}

But the sprites are still overlapping each other and do not form a proper row.
What am i doing wrong here and how can i rectify it?


Solution

  • If the sprite's res is 128x128 pixels.
    And this sprite's Pixels To Units is 100.

    So your tileWidth will be: renderer.bounds.size.x = 128/100 = 1.28
    But you use int: (int)renderer.bounds.size.x = (int)1.28 = 1
    and this is why your sprites overlapping each other.

    float tileWidth = (float)tileSet[0].renderer.bounds.size.x;