Collider.OnTriggerEnter(Collider)

매뉴얼로 전환

파라미터

otherThe other Collider involved in this collision.

설명

When a GameObject collides with another GameObject, Unity calls OnTriggerEnter.

OnTriggerEnter happens on the FixedUpdate function when two GameObjects collide. The Colliders involved are not always at the point of initial contact.

Note: Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.

To use the following code sample, create a primitive GameObject, and attach a Collider and Rigidbody component to it. Enable Collider.isTrigger and Rigidbody.isKinematic. When the primitive collides, OnTriggerEnter gets called. In this example, the direction immediately reverses. When the GameObject exits the collision, Unity calls OnTriggerExit, changing the color.

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; } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961