kUr4m4
kUr4m4

Reputation: 720

automatically refit boxcollider2D upon sprite change

I have a prefab with a sprite renderer and a boxcollider2D that I use for the bullets in my game.

The sprites I use for each type of bullet are of different sizes and so, when I instantiate a bullet with a different sprite size than the generic bullet from my prefab, the boxcollider doesn't always match the sprite size.

I noticed that when add a boxcollider to my gameobject that it automatically fits the sprite. Is there any way to make this autofit call from the script? Or the only way is to add the collider at runtime?

Upvotes: 2

Views: 5765

Answers (1)

axwcode
axwcode

Reputation: 7824

You can auto fit the collider to the size of the sprite like this:

renderer.bounds.size

Which will give you the size of the sprite.

Then you can make the current collider's size accordingly:

 Vector3 v = renderer.bounds.size; 

 BoxCollider2D b = collider2D as BoxCollider2D;

 b.size = v;

Upvotes: 9

Related Questions