Unity | Match BoxCollider2D to sprite size
Published by Pavel Nakonechnyy on (updated: ) 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.
552