Creating A Modular Waypoint System (part 2)

Enemy AI moving from Point A to Point B

Simon Truong
3 min readAug 11, 2021

--

Now that we have created our physical waypoint game objects and have applied them to the AI script component. It is time to continue with scripting a method to allow the AI to stop and wait a few seconds before turning back and reversing the order in the waypoint list. (ie. from 1 > 2 >3 to 3 > 2 > 1).

Enemy AI scripting

This is where we last left off

Continuing on with the void Update, we need to make some adjustments from the previous setup. Since we will want the Enemy AI to pause a few seconds after reaching their final destination we need to utilize a coroutine.

It is time to make use of the two bools which we had setup previously. The first bool “_targetReached” will be placed within the IF statement. This bool will basically control when the enemy has reached one of the waypoints to either stop or continue if there was more waypoints.

IF statement changed by adding an bool

Next we are going to start an coroutine by using the method “IEnumerator”. This will give us access to the “new wait for seconds” function which can let us pause the AI for a set duration.

In the coroutine we first create an IF statement followed by an else IF statement. These first two statements will control the wait for seconds function.

The first IF statement tracks when the current target equals zero (so the starting point) we will yield all actions and wait for 2 seconds.

The second Else IF statement tracks when current target equals the maximum waypoint list count (so the finish point) we will also yield all actions and wait for a set duration.

We add an -1 at the end of the waypoint.Count is because the list starts from 0 and not 1.

Scripting for Reverse movement

Finally we are going to create two more IF statements which controls the looping of the waypoints.

The first IF statement checks if the bool “reverse” is equal to true, when it is true we will trigger the minus sequence of the current target. We do this until our target as reached back to the beginning were we reset our waypoint target to zero and set the bool “reverse” back to false.

Then we have an Else IF statement which tracks when “reverse” is false we do the opposite where we have an addition in the sequence. Then use another IF statement to check when the current target as reach the maximum target, we switch the bool back to true and have the minus sequence start again.

We finish of the coroutine by setting the bool “targetReached” back to false so the whole sequence can be repeated again in a forever loop.

Save and return back to Unity and see your AI move in the set location back and forth.

--

--

Simon Truong

A Designer, an Illustrator and a massive tech geek aspiring to become a professional Unity Developer.