Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting width of 2d object in unity 3d

Tags:

unity3d

I'm using the new 2d tools in Unity3d, and I have a game object with a 2d polygonal collider attached to it. I just want to understand how to get the width of this object! Why is this so difficult? The collider nor the game object have anything that has a "bounds" or "size" property. Even if they did, however, how would I extrapolate width from a vector3 object? From what I understand about vector3 objects, they give a length (magnitude) from the origin of the scene. So how could I use distance from the scene's origin to determine with width of my game object? Any help would be greatly appreciated.

like image 463
Tyler Jones Avatar asked Feb 27 '14 06:02

Tyler Jones


2 Answers

There are two ways(at least) to get this.

  • The 1st is to user Renderer.bounds;
  • The 2nd is to use Collider.bounds

var renderer = gameObject.GetComponent<Renderer>();
int width = renderer.bounds.size.x;

or


var collider2D= gameObject.GetComponent<Collider2D>();
var collider = collider2D.collider; //Edit, thanks to Arttu's comment!
int width = collider.bounds.size.x;

For your 2D case, the former might be more appropriate.

like image 174
David Avatar answered Sep 17 '22 20:09

David


According to this post, looks like 2D colliders indeed should have the missing bounds variable, and it will be made available in a future release.

So looks like for now you'll have to make do with a workaround. One could be to add a Sprite Renderer component to your GameObject, add a dummy image to it and set it disabled so it's never visible. Then you can use gameObject.renderer.bounds to get the sprite bounds.

like image 21
Arttu Peltonen Avatar answered Sep 17 '22 20:09

Arttu Peltonen