Version: 2022.3
Language : English
OnCollision events
Create and configure a trigger collider

OnTrigger events

Trigger collidersAn invisible shape that is used to handle physical collisions for an object. A collider doesn’t need to be exactly the same shape as the object’s mesh - a rough approximation is often more efficient and indistinguishable in gameplay. More info
See in Glossary
don’t cause collisionsA collision occurs when the physics engine detects that the colliders of two GameObjects make contact or overlap, when at least one has a Rigidbody component and is in motion. More info
See in Glossary
. Instead, they detect other colliders that pass through them, and call functions that you can use to initiate events.

Example uses for triggers include:

  • When the player reaches a specific area at the end of a corridor, activate a cinematic cutscene.
  • When the player character walks within a space in front of a sliding door, trigger an animation to open the door.
  • When projectiles pass through a trigger collider in the far distance, disable or destroy the projectile.

Working with trigger colliders primarily involves the following API functions:

  • Collider.OnTriggerEnter: Unity calls this function on a trigger collider when it first makes contact with another collider.
  • Collider.OnTriggerStay: Unity calls this function on a trigger collider once per frame if it detects another Collider inside the trigger collider.
  • Collider.OnTriggerExit: Unity calls this function on a trigger collider when it ceases contact with another collider.

The following example prints a message to the Console when Unity calls each function.

using UnityEngine;
using System.Collections;

public class DoorObject : MonoBehaviour
{
    // “other” refers to the collider on the GameObject inside this trigger
    void OnTriggerEnter (Collider other)
    {
        Debug.Log ("A collider has entered the DoorObject trigger");
    }

    void OnTriggerStay (Collider other)
    {
        Debug.Log ("A collider is inside the DoorObject trigger");
    }
    
    void OnTriggerExit (Collider other)
    {
        Debug.Log ("A collider has exited the DoorObject trigger");
    }
}

For examples of practical applications for OnTrigger events, see Example scripts for collider events.

OnCollision events
Create and configure a trigger collider
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961