To capture trigger events, you'll need to create a new script by following these steps:
- Create a new C# script in the Scripts folder, name it EnemyBehavior, and then drag it into Enemy.
- Add the following code and save the file:
public class EnemyBehavior : MonoBehaviour
{
// 1
void OnTriggerEnter(Collider other)
{
//2
if(other.name == "Player")
{
Debug.Log("Player detected - attack!");
}
}
// 3
void OnTriggerExit(Collider other)
{
// 4
if(other.name == "Player")
{
Debug.Log("Player out of range, resume patrol");
}
}
}
- Click on Play and walk over to the Enemy to set off the first notification:
- Walk away from the Enemy to set off the second notification.
Here's a breakdown of the preceding code:
- OnTriggerEnter() is fired whenever an object enters...