- Home /
When setting a transform size with attached SpriteRenderer, why is this not the actual pixel size?
For example, I have a Transform with SpriteRenderer attached. The transform size is set to Vector3(3, 3, 0).
Now I have a loop that runs through as the code below shows, but these instantiated objects always have gaps and spaces between them. What am I missing?
for(int x = 0; x < 100; x++)
{
for(int y = 0; y < 100; y++)
{
Vector3 pos = new Vector3(this.transform.position.x+(x * 3),this.transform.position.y+(y * 3), 0);
GameObject land = (GameObject)Instantiate(landObject,pos,this.transform.rotation);
}
}
Thanks to anyone who replies with an answer!
Answer by Stone-Legion · Dec 06, 2013 at 01:08 PM
Discovered the solution on my own.
For anyone wondering, its quite easy. I had to use renderer.bounds.size.x and y to do the trick.
for(int x = 0; x < 25; x++)
{
for(int y = 0; y < 25; y++)
{
Vector3 pos = new Vector3(this.transform.position.x+ (x *landObject.transform.renderer.bounds.size.x),
this.transform.position.y-( y *landObject.transform.renderer.bounds.size.y),
0);
GameObject land = (GameObject)Instantiate(landObject,pos,this.transform.rotation);
}
}
Answer by Tomer-Barkan · Dec 06, 2013 at 01:17 PM
As in all other unity objects, the transform's scale is relative to the model size. In case of sprites, the model size is the size of the texture. By default, the 2D mode uses 1 meter = 100 pixels, so if you have a 100x100 pixel texture, and the scale is (1 , 1) it will occupy 1 meter of world space.
If on the other hand you have a 200x200 pixel texture in your sprite, and the scale is (1 , 1), the size of the object in the world will be 2 meters.
So to calculate the world size of the sprite (assuming you left the default 100 pixels per unit when importing the sprite):
Texture2D spriteTexture = landObject.GetComponent<SpriteRenderer>().sprite.texture;
Vector3 spriteSize = new Vector3(spriteTexture.width / 100f, spriteTexture.heigh / 100f, 0);
Then you can use this instead of 3:
for(int x = 0; x < 100; x++)
{
for(int y = 0; y < 100; y++)
{
Vector3 pos = new Vector3(this.transform.position.x+(x * spriteSize.x),this.transform.position.y+(y * spriteSize.y), 0);
GameObject land = (GameObject)Instantiate(landObject,pos,this.transform.rotation);
}
}
This seems to cause the sprites to spread apart even further. I'll try modifying it a bit as I think your approach is more correct if it is written properly - $$anonymous$$e causes the sprites, while side by side, to show half a pixel off at some points. Thanks.
Don't forget to check that the setting is indeed that 100 pixels = 1 meter in the world. This is defined in the sprite importer.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123548im_/https://answers.unity.com/themes/thub/images/avi.jpg)