2
\$\begingroup\$

I'm trying to get the width and height of a 2D GameObject. My GameObject is simply a prefab created using sprite.

I have tried solutions from other posts but they don't work for me:

Vector2 size = myGameObject.GetComponent<CircleCollider2D>().bounds.size;
float width = size.x;
float height = size.y;

and

Vector2 size = myGameObject.GetComponent<Collider2D>().bounds.size;
float width = size.x;
float height = size.y;

My prefab has a Circle Collider 2D but x and y always returns 0

I'm using Unity 5.5.0f3, not sure if previous solutions apply to this version.

\$\endgroup\$
  • 1
    \$\begingroup\$ have you tried receiving the collider as an actual CircleCollider2D, and accessing its radius variable? Circle geometry typically commits a height and a width, as the x and y values are always the same, I.e. its radius. Alternatively, BoxCollider2D should contain actual values for both width and height. \$\endgroup\$ – Gnemlock Dec 31 '16 at 4:29
  • \$\begingroup\$ Try GetComponent<Transform>().lossyScale.x for width and GetComponent<Transform>().lossyScale.y for height. \$\endgroup\$ – JDSweetBeat Dec 31 '16 at 6:26
2
\$\begingroup\$

I think you should use CircleCollider2D.radius

So get the radius and multiply it by 2.

var size = GetComponent<CircleCollider2D>().radius;
Debug.Log(2 * size);
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.