Creating a Sentry in Unity

Ryan Sweigart
2 min readJun 17, 2021

Objective: Create an enemy AI that will patrol a set of waypoints.

“They told me I could be anything I wanted, so I became an NPC.”

First we create a List to hold the waypoints. We’ll write the code such that having no waypoints is valid — that would make a stationary sentry.

We can assign the waypoints in the inspector. In the example below, the sentry will move to A, then to B, back to A, then to C, which is his original destination. This pattern will repeat, creating an L-shaped path.

If the sentry has any waypoints assigned, it will initially move towards the first one (at index 0). When it is close enough to its destination (within our defined _destinationOffset), it will perform a modulo operation (the “%” operator in our code below) to determine the index of the next waypoint. This will give us our looping behavior. When we hit the last waypoint (index 3 in this example), the modulus of the next index will be 0 ([3+1] % 4 = 4 % 4 = 0).

--

--