Introduction
In this article we are going to see how the OnTriggerEnter method works in Unity. This function will allow us to know when the Collider of a certain GameObject has enter another Collider that is specially configured to be able to detect.
OnTriggerEnter and OnTriggerExit are very similar methods but it changes the moment in which the execution of these methods happens, knowing exactly these moments will allow us to build solutions.
The following video has summarized information about the OnTrigger events, how to setup the components and how to define the events in a script.
OnTriggerEnter Method in Unity
The OnTriggerEnter method is defined in the MonoBehaviour class. That is to say that any new Script by default will have it by inheritance.
Several conditions must be met for OnTriggerEnter to run.
The first is that there must be two GameObjects with Colliders involved, one of the Colliders must be in Trigger mode, for this you must check the box “Is Trigger” in the inspector.
In addition, at least one of the GameObjects involved must be assigned a RigidBody component, because OnTriggerEnter is related to the physical part of the engine.
Declare OnTriggerEnter
The fact that it is defined in the MonoBehaviour class and a new default Script does not mean that we will automatically have OnTriggerEnter in our Script, we must declare it and we do it in the following way:
private void OnTriggerEnter(Collider c){ //Acciones a realizar cuando se detecta una entrada al Trigger. }
If the conditions are met, this method will run automatically, so inside we write everything that needs to be done when that happens.
The parameter “Collider c” that receives the method, is the Collider of the GameObject that came into contact with the Trigger. We can use this parameter to do many things, for example get the GameObject that has assigned that collider, we do this simply with:
c.gameObject
From there we can read any other component assigned to GameObject, its tag, its layer, modify what we need and we are allowed to modify, execute methods defined in Scripts that may be assigned and many more actions.
To learn more about programming functions with parameters I invite you to read this article.
Conclusion
The OnTriggerEnter method allows us to detect when two GameObjects overlap their Colliders, so we can apply all the necessary actions.
OnTriggerEnter runs automatically, for this to happen there must be some conditions, the first is that there must be two GameObjects with Colliders involved and one of them in Trigger mode and the second is that at least one of the GameObjects must have a RigidBody component assigned.