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:

(They do continue on their path after a few seconds 😉)

--

--

--

Game Developer | Game Design and Literature Graduate

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Let’s Encrypt With Certbot

Stale read on Aurora version 2.07.3

Campus North and Tech for Life Placement

NFS Network File Share

Implementing our own Malloc function and Memory Management Schemes in C/C++ Using Linked List

Building A Dashboard D3.JS & JavaScript: Upstream Oil & Gas Data (Part 1 of 2)

Dynamic persistent volume provisionning with Openshift and the Ceph container

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marcus Ansley

Marcus Ansley

Game Developer | Game Design and Literature Graduate

More from Medium

Embedded GUI Development

Kotlin code sample using LVGL KT

Branching on a GPU

Reverse engineering Fallout 2

Adding proximity detection so enemies can ram player