Give The Guards Some Functional Eyes!
Now that the security guards are nicely patrolling the auction house, lets allow them to see the thief and react!
Today’s Objective: Give the guards sight by sending Raycasts from the guard’s head forward in the direction he’s facing.
Note: I am using an asset from the Unity Asset Store which I own to improve the AI’s detection capabilities. This asset is totally optional, but since I also want to add proximity detection and some other features later, I am using it. You can still follow along for the on-player-detected behaviours.
I won’t go over how to set up the asset since that’s not what this post is about. The main thing to know is that I now have the ability to call a function using Unity Events once when the player is detected.
Ok, now onto my code.
In a new class called “AIPlayerDetection”, I’ve added variables to store the asset’s sensor component references, and some private variables to store the current state of detection.
I use “TryGetComponent( )” in Awake because I want the waypoint patroller and animator components to be optional, not required.
The “PlayerEnteredDetection( )” method is called by the asset script which monitors the GameObjects currently within view.
You could easily change the behaviour to, for example, require the guard to start running towards the player and only activate the cutscene when they are close enough.