0
0
Unityframework~5 mins

3D colliders in Unity

Choose your learning style9 modes available
Introduction

3D colliders help your game objects know when they touch or bump into each other. They make games feel real by detecting collisions.

When you want to detect if a player hits a wall or obstacle.
When you want to know if a bullet hits an enemy.
When you want objects to bounce or stop moving after hitting something.
When you want to trigger an event when two objects touch, like opening a door.
When you want to prevent characters from walking through each other.
Syntax
Unity
gameObject.AddComponent<BoxCollider>();

// Or in the Unity Editor, add a Collider component like BoxCollider, SphereCollider, CapsuleCollider, or MeshCollider to your GameObject.

3D colliders come in different shapes like BoxCollider, SphereCollider, CapsuleCollider, and MeshCollider.

You can add colliders in code or by using the Unity Editor's Inspector window.

Examples
Adds a box-shaped collider to the game object in code.
Unity
gameObject.AddComponent<BoxCollider>();
Adds a sphere-shaped collider to the game object in code.
Unity
gameObject.AddComponent<SphereCollider>();
Add a capsule collider using the Unity Editor without writing code.
Unity
// In Unity Editor:
// Select your GameObject > Click Add Component > Choose CapsuleCollider
Sample Program

This script adds a box collider to the object it is attached to. When the object hits another, it prints the name of the other object.

Unity
using UnityEngine;

public class ColliderExample : MonoBehaviour
{
    void Start()
    {
        // Add a BoxCollider to this GameObject
        BoxCollider box = gameObject.AddComponent<BoxCollider>();
        box.size = new Vector3(2, 2, 2);
        Debug.Log("BoxCollider added with size " + box.size);
    }

    void OnCollisionEnter(Collision collision)
    {
        Debug.Log("Collided with " + collision.gameObject.name);
    }
}
OutputSuccess
Important Notes

Make sure at least one object has a Rigidbody component for collision events to work properly.

MeshColliders can be expensive for performance; use simple colliders when possible.

Use 'Is Trigger' on colliders if you want to detect overlaps without physical collision.

Summary

3D colliders detect when objects touch or collide in your game.

You can add different shapes of colliders in code or the Unity Editor.

Colliders work best with Rigidbody components to detect collisions and trigger events.