0
0
Unityframework~5 mins

Collider2D types (box, circle, polygon) in Unity

Choose your learning style9 modes available
Introduction

Colliders in Unity help detect when objects touch or overlap. Different shapes fit different object types better.

Use a BoxCollider2D for square or rectangular objects like crates or doors.
Use a CircleCollider2D for round objects like balls or coins.
Use a PolygonCollider2D for irregular shapes like characters or complex platforms.
Syntax
Unity
AddComponent<BoxCollider2D>()
AddComponent<CircleCollider2D>()
AddComponent<PolygonCollider2D>()

Each collider type is a component you add to a GameObject in Unity.

You can adjust size and shape in the Inspector or by code.

Examples
Adds a box-shaped collider to the object.
Unity
gameObject.AddComponent<BoxCollider2D>();
Adds a circle-shaped collider to the object.
Unity
gameObject.AddComponent<CircleCollider2D>();
Adds a polygon-shaped collider to the object.
Unity
gameObject.AddComponent<PolygonCollider2D>();
Sample Program

This script adds three different 2D colliders to the same GameObject and prints their properties.

Unity
using UnityEngine;

public class ColliderExample : MonoBehaviour
{
    void Start()
    {
        // Add a BoxCollider2D
        var box = gameObject.AddComponent<BoxCollider2D>();
        box.size = new Vector2(2f, 3f);

        // Add a CircleCollider2D
        var circle = gameObject.AddComponent<CircleCollider2D>();
        circle.radius = 1.5f;

        // Add a PolygonCollider2D
        var polygon = gameObject.AddComponent<PolygonCollider2D>();
        polygon.points = new Vector2[] {
            new Vector2(0, 0),
            new Vector2(1, 0),
            new Vector2(1, 1),
            new Vector2(0, 1)
        };

        Debug.Log("Box size: " + box.size);
        Debug.Log("Circle radius: " + circle.radius);
        Debug.Log("Polygon points count: " + polygon.points.Length);
    }
}
OutputSuccess
Important Notes

PolygonCollider2D lets you define any shape by setting points.

BoxCollider2D and CircleCollider2D are simpler and faster for performance.

You can have multiple Box, Circle, or Polygon colliders on a GameObject if needed for compound shapes.

Summary

BoxCollider2D is best for rectangles and squares.

CircleCollider2D fits round objects.

PolygonCollider2D works for complex shapes by defining points.