Coin to Lure AI Guards Functionality (using UnityEvents) [2]
As touched on in the previous article, we’ll now need our guards to listen to and respond to the ‘coinTossed’ custom event. Over in the Guard class, I’ve setup a ListenToEvents method which will get called during Start. This method will ensure the guards are listening to any of the events they need to listen to, which for now is just the one Vector3 event:

The event itself currently consists of an if statement, which uses the Vector3.Distance method to assess whether the guard’s distance from the coin is less than the _coinDetectionDistance float (set to 5f at the moment), and some logic nested inside it to change a boolean, start the moving animation, and set the destination for the NavMeshAgent component:

The ‘_coinDetected’ boolean is now being used as one of two conditions in the normal walk/navigation cycles of the AI, so that whenever it’s set to true their usual movement pattern is paused. It’s not quite how I’d like it personally, but I’ve also got a new if statement under Update to run the logic for the guard’s movement towards the coin. I think I’d rather have this logic, and probably most of the logic currently under Update, within some dedicated coroutines that’ll wait until the destination has been reached before progressing. Anyway, that’ll take some tidying, but for now all this means that I’ll be checking for whether the agent has reached its destination and, if it has, I’m calling the same ‘WaitBeforeMoving’ coroutine I’m using for the main walk cycle:

As for the end result, it’s currently looking like this in the Game view:
