Digital Leadership & Soft Skills

Unity | Match BoxCollider2D to sprite size

Published by Pavel Nakonechnyy on in GameDev.
Unity | Match BoxCollider2D to sprite size

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.

518