[Tutorial] Dynamically resizing colliders to match sprites in Unity

In Trimmer Tycoon you grow your shop's popularity by placing decorations. The decorations are clickable and display a right-click menu that allows the player to sell or move the decoration piece. The sprites, however, are of different sizes, so the collider has to be resized for every sprite individually. Here's how you do it in Unity:

Whenever you want to update a gameobject's BoxCollider2D's size to match its sprites size, just call this function. If the script is not attached to the gameobject you want to resize, replace "gameObject" with that gameobject.

void UpdateCollider(){
	gameObject.GetComponent<BoxCollider2D>().size = gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size;
	gameObject.GetComponent<BoxCollider2D>().offset = gameObject.GetComponent<SpriteRenderer>().sprite.bounds.center;
}

In our case we just check if the sprite has changed like this:

Update(){
	if(currentSprite != GetComponent<SpriteRenderer>().sprite){
  		currentSprite = GetComponent<SpriteRenderer>().sprite;
		UpdateCollider();
	}
}

If you have an animation and you don't want to have to animate the collider as well, just stick the above script in Update() or LateUpdate(). If you're doing this, remember to change the collider type if you aren't dealing with SquareColliders.

Congratulations, you no longer have to worry about resizing the object's collider, you have a script that does it for you!