# Unity: How can I get the width of a gameobject?

I'm trying to make sure a gameobject (2D sprite, say, panda) stays to the left of another (say, bamboo), regardless of the former's size. I thought I could take the bamboo's location, and deduct the width of the panda from it.

Something like this:

Here's my code so far:

foreach (GameObject panda in midBambooStack)
{
Vector3 newPosition = new Vector3(midBamboo.transform.position.x - panda.transform.lossyScale.x, panda.transform.position.y, panda.transform.position.z);
panda.transform.position = newPosition;
}


But what I end up is that the panda goes right in the middle of the bamboo, so I'm assuming the lossyScale.x bit is wrong.

Any suggestions?

EDIT: Here's my hierarchy, if it means something.

• is there any rotation on the pandas? – Gnemlock Aug 14 '16 at 8:34
• @Timelord64, nope, I disabled them, because I had issues with dragging and dropping and rigidbodies. – zack_falcon Aug 14 '16 at 8:37
• are you decreasing or increasing scale? is there are any parent-child or the sprite is root? – Sourav Paul Aug 14 '16 at 9:03
• @SP. Scale? I'm sorry, I don't think I understand your question. Each of those pandas are a different gameobject. I updated the question with a pic of my hierarchy. – zack_falcon Aug 14 '16 at 9:23
• what happens if you just use regular scale? Transform.lossyScale specifically gets you the global scale, but in your case, the pandas are not children of any other object. Since they do not inherit a scale from any other object, you should be fine with regular scale. I believe @SP means did you load in the smallest panda, and scale it up to the larger sizes, or load in the largest panda, and scale it down to the smaller sizes. – Gnemlock Aug 14 '16 at 12:08

## 1 Answer

This will rely on the Pixel Per Unit value of your sprite. If you do not have a 1:1 ratio, then a value of "1" for your LocalScale.x will not be the same width as your sprite.

Either set the sprite's Pixel Per Unit value to a 1:1 ratio, or manually calculate the ratio multiplier:

float PixelUnits;

private void CalculatePixelUnits()
{
PixelUnits = Sprite.rect.width / Sprite.bounds.size.x;
}


In the above code you would pass in your Panda sprite.

With this value you should then be able to position these Pandas properly:

foreach (GameObject panda in midBambooStack)
{
Vector3 newPosition = new Vector3(midBamboo.transform.position.x - panda.transform.localScale.x * PixelUnits, panda.transform.position.y, panda.transform.position.z);
panda.transform.position = newPosition;
}