Version: 2022.2

MonoBehaviour.OnTriggerEnter(Collider)

切换到手册

参数

other 该碰撞中涉及 Collider

描述

GameObject 与另一个 GameObject 碰撞时,Unity 会调用 OnTriggerEnter。

当两个 GameObjects 碰撞时,OnTriggerEnter 会在 FixedUpdate 函数上发生。涉及的碰撞体并不始终在初始接触点处。

Note: Both GameObjects must contain a Collider component. At least one of them must have Collider.isTrigger enabled, and contain a Rigidbody.
If one of the GameObjects has Collider.isTrigger enabled or both GameObjects do not have a Rigidbody component, no physical collision happens. In both cases, Unity still calls OnTriggerEnter.

For a physical collision to occur, both GameObjects should contain a Collider component with Collider.isTrigger disabled, and contain a Rigidbody component. For more information see Colliders.

using UnityEngine;

public class Example : MonoBehaviour { private float speed = 2f;

//Moves this GameObject 2 units a second in the forward direction void Update() { transform.Translate(Vector3.forward * Time.deltaTime * speed); }

//Upon collision with another GameObject, this GameObject will reverse direction private void OnTriggerEnter(Collider other) { speed = speed * -1; } }