📜  ontriggerenter - C# (1)

📅  最后修改于: 2023-12-03 15:33:17.618000             🧑  作者: Mango

OnTriggerEnter - C#

OnTriggerEnter is a method in the MonoBehaviour class in Unity game engine. It is used to detect when a GameObject with a Collider component enters another GameObject's trigger Collider.

Syntax
void OnTriggerEnter(Collider other)
  • other: The Collider component of the other GameObject which entered the trigger.
Example
using UnityEngine;

public class MyTriggerScript : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        Debug.Log("Entered trigger!");
    }
}

In this example, when some other GameObject enters the trigger which the MyTriggerScript component is attached to, Entered trigger! will be logged to the console.

Notes
  • Both GameObjects must have at least one Collider component, and one of them must have isTrigger set to true.
  • If the other GameObject has a RigidBody component, it must be marked as isKinematic in order for OnTriggerEnter to be called.
  • OnTriggerEnter is called on the object that has the script attached to it, not the object that entered the trigger.
Conclusion

OnTriggerEnter is a useful tool for detecting when GameObjects collide in Unity. It can be used for a variety of tasks, such as triggering events or activating and deactivating GameObjects.