Collider.OnTriggerEnter(Collider)

Switch to Manual

Parameters

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

Description

Collider other 事件进入该触发器时调用 OnTriggerEnter

此消息被发送到触发器 Collider 和触发器 Collider 所属的 Rigidbody(如果有), 以及接触该触发器的 Rigidbody(或 Collider,如果没有 Rigidbody)。

注意:如果其中一个 Colliders 还附加了 Rigidbody,则仅发送触发器事件。触发器事件将发送到已禁用的 MonoBehaviours,以便允许启用 Behaviours,以响应碰撞。碰撞后,在 FixedUpdate 上发生 OnTriggerEnter。不保证涉及的 Colliders 在初始接触点。

注意:从技术上讲,OnTriggerEnter 不是 Collision 的一部分。这是一个 MonoBehaviour 函数。

以下 CS 示例说明触发器如何能够与球体 GameObject 交互。该 GameObject 是在 Awake 中创建的。当该立方体与此球体交互时,调用 OnTriggerEnterOnTriggerStayOnTriggerExitUpdate 将该立方体向前/向后以及向左/向右移动。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Example : MonoBehaviour { public bool enter = true; public bool stay = true; public bool exit = true; public float moveSpeed;

void Awake() { // move and reduce the size of the cube transform.position = new Vector3(0, 0.25f, 0.75f); transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);

// add isTrigger var boxCollider = gameObject.AddComponent<BoxCollider>(); boxCollider.isTrigger = true;

moveSpeed = 1.0f;

// create a sphere for this cube to interact with GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.gameObject.transform.position = new Vector3(0, 0, 0); sphere.gameObject.AddComponent<Rigidbody>(); sphere.gameObject.GetComponent<Rigidbody>().isKinematic = true; sphere.gameObject.GetComponent<Rigidbody>().useGravity = false; }

void Update() { transform.Translate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical") * moveSpeed); transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal") * moveSpeed); }

private void OnTriggerEnter(Collider other) { if (enter) { Debug.Log("entered"); } }

// stayCount allows the OnTriggerStay to be displayed less often // than it actually occurs. private float stayCount = 0.0f; private void OnTriggerStay(Collider other) { if (stay) { if (stayCount > 0.25f) { Debug.Log("staying"); stayCount = stayCount - 0.25f; } else { stayCount = stayCount + Time.deltaTime; } } }

private void OnTriggerExit(Collider other) { if (exit) { Debug.Log("exit"); } } }
using UnityEngine;

public class Example : MonoBehaviour { // Destroy everything that enters the trigger void OnTriggerEnter(Collider other) { Destroy(other.gameObject); } }