Changing BoxCollider2D Size Based On Sprite Size

Now that I have some objects randomly being generated I need to make sure that the BoxCollider2D matches the size of the sprite. I am cheating a little bit since all of my objects are boxes but here you can see how I go from the desk:

Ember 4

To the dresser:

Ember 3

To the crate:

Ember 2

And they are all the same exact prefab, randomly picking a sprite from this array:

Ember

The code is really simple, it’s actually only a few lines:

var renderer = GetComponent<spriterenderer> ();
renderer.sprite = sprites [Random.Range(0, sprites.Length)];
 
// Change collider to match the size of the sprite
var collider = GetComponent<boxcollider2d> ();
collider.size = renderer.bounds.size;

Subscribe To My Mailing List

Want to learn how to make a game? Not sure where to start? Even if you are a seasoned game maker there is still a lot you can learn from my mailing list. I'll be covering tips and tricks for how to build, release and market games each month.

Simply sign up for my mailing list and also get access to a 50% off discount code for my eBooks and other content. I promise to not spam your inbox!

Join Now