Collider.OnTriggerEnter(Collider)

切换到手册

参数

other该碰撞中涉及的其他 Collider。

描述

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

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

注意:两个 GameObjects 都必须包含 Collider 组件。其中一个必须启用 Collider.isTrigger,并包含 Rigidbody。如果两个 GameObjects 都启用了 Collider.isTrigger,则不会发生碰撞。如果两个 GameObjects 都没有 Rigidbody 组件,情况同样如此。

要使用下面的代码示例,请创建原始 GameObject,并向它附加 ColliderRigidbody 组件。启用 Collider.isTrigger 和 Rigidbody.isKinematic。原始游戏对象碰撞时,将调用 OnTriggerEnter。在本例中,方向立即反转。当 GameObject 退出碰撞时,Unity 调用 OnTriggerExit,更改颜色。

using UnityEngine;

public class exampleScript : MonoBehaviour { private float speed = 2f; Renderer rend; int colorPicker = 0;

private void Start() { rend = GetComponent<Renderer>(); transform.position = Vector3.zero; transform.rotation = Quaternion.Euler(0, 90, 0);

//Create two GameObjects to act as walls GameObject leftWall = GameObject.CreatePrimitive(PrimitiveType.Cube); GameObject rightWall = GameObject.CreatePrimitive(PrimitiveType.Cube); //Move the walls to the correct positions leftWall.transform.position = new Vector3(-10, 0, 0); rightWall.transform.position = new Vector3(10, 0, 0); //Scale the walls leftWall.transform.localScale = new Vector3(1, 2, 1); rightWall.transform.localScale = new Vector3(1, 2, 1); }

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

//When the Primitive collides with the walls, it will reverse direction private void OnTriggerEnter(Collider other) { speed = speed * -1; colorPicker = Random.Range(0, 10); }

//When the Primitive exits the collision, it will change Color private void OnTriggerExit(Collider other) { switch (colorPicker) { case 0: rend.material.color = Color.white; break; case 1: rend.material.color = Color.cyan; break; case 2: rend.material.color = Color.blue; break; case 3: rend.material.color = Color.black; break; case 4: rend.material.color = Color.red; break; case 5: rend.material.color = Color.green; break; case 6: rend.material.color = Color.grey; break; case 7: rend.material.color = Color.magenta; break; case 8: rend.material.color = Color.yellow; break; case 9: rend.material.color = Color.gray; break; } } }