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!
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);
}
}
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);
}
}