触发碰撞体不会导致碰撞。相反,它们会检测穿过它们的其他碰撞体,并调用可用于发起事件的函数。
触发器的示例用法包括:
触发碰撞体的处理主要涉及以下 API 函数:
Collider.OnTriggerEnter:当碰撞体首次与另一个碰撞体接触时,Unity 会在触发碰撞体上调用此函数。Collider.OnTriggerStay:如果触发碰撞体在其内部检测到另一个碰撞体,Unity 会在触发碰撞体上每帧调用一次此函数。Collider.OnTriggerExit:触发碰撞体停止与另一个碰撞体接触时,Unity 在触发碰撞体上调用此函数。以下示例为当 Unity 调用每个函数时会向控制台打印消息。
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");
}
}
有关 OnTrigger 事件的实际应用示例,请参阅碰撞体事件脚本示例。