Getting width of 2d object in unity 3d

I use 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 it so hard? A collider or game object has everything that has the property of "borders" or "size". However, even if they did, how would I extrapolate the width from the vector3 object? From what I understand about vector3 objects, they give the length (value) from the beginning of the scene. So, how could I use the distance from the beginning of the scene to determine the width of my game object? Any help would be greatly appreciated.

+6
source share
2 answers

According to this post , it looks like 2D colliders really need to have a variable of missing borders, and it will be available in a future version.

So it looks now, now you have to get around the workaround. You can add the Sprite Renderer component to your GameObject, add a dummy image to it, and disable it so that it is never visible. Then you can use gameObject.renderer.bounds to get the borders of the sprites.

+5
source

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


 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 comment! int width = collider.bounds.size.x; 

For your 2D application, the former may be more appropriate.

+14
source

All Articles