Unity | Match BoxCollider2D to sprite size
Published in GameDev.

Small script, which can be useful for objects that changes sprites with multiple resolutions and sizes.
public static void MatchToSize(GameObject obj, BoxCollider2D collider = null, SpriteRenderer renderer = null) {
collider = collider ?? obj.GetComponent();
renderer = renderer ?? obj.GetComponent();
Vector2 S = renderer.sprite.bounds.size;
collider.size = S;
collider.offset = Vector2.zero;
}
UPD: Updated to support better optimization by calling with cached Components in args.
458