How to make a basic patrolling system in Unity/C#

Let’s see how to implement a basic waypoints-based patrolling system for a character unit!

🚀 Find all of my Unity tutorials on Github!

This article is also available on Medium.

This tutorial is available either in video format or in text format – see below 🙂

Get the scripts for this tutorial on my Github 🙂

A bit of context

Let’s say that you just finished designing your level, and you’ve placed your enemies here and there, all fierce and mighty. Now, when your hero comes around, the enemies will go to him and try to attack – they will switch their state from an “idle” state to an “attack” state, for example, if you’re using a finite-state machine

But then, should the enemies just stay still when in “idle” mode? Wouldn’t it be better if they were patrolling back and forth in the level to keep an eye out for trouble?

Today, we’re going to work on implementing a simple patrolling system for an enemy, represented by a cube. The unit will walk steadily between a sequence of waypoints and, when it reaches the last one, it will loop back to the first one.

Preparing the scene

To begin with, let’s actually add a cube for our enemy in the scene. I’ll give it a basic red colour and place it at the origin point:

Then, I’ll prepare the waypoints to define its path. These waypoints will be empty game objects: this way, they will be invisible but we’ll be able to use them as target transforms for our enemy movement.

To make them easier select in the scene view, however, we can give them a special icon and have them show with little gizmos in the view: just go to the Inspector panel and, at the very top, next to the game object’s name, click on the dropdown to pick one icon from Unity’s built-ins. As soon as you’ve chosen an icon, you’ll see that there is now a blue dot at the position of the object in the scene view:

Here, I’m placing one waypoint at the current position of the enemy and then three others so that the unit walks a square path.

Coding up a simple patrolling routine

With that setup done, it’s time to start coding!

Let’s go ahead and create a C# script called Patrol.cs that we add to our enemy game object. Then, let’s open up this script and, for now, remove the start and update methods:

Adding some variables

The first thing we need is a reference to our waypoints, so we’ll create an array of Transforms called waypoints. I’ll make it public so it shows up in the Inspector and go back to Unity to assign them:

Note that, instead, you could also have an array of Vector3s and bake the initial positions of the Transforms: if you’re sure that your waypoints will always stay static at the same place, it’s more optimised to just compute their positions once. But by using Transforms, we’ll be able to make the waypoints move if we want and our unit will automatically recompute the path to it!

The second thing we have to do is store the index of the current target waypoint in a (private) integer variable called _currentWaypointIndex. This counter will get incremented gradually as the unit goes through its waypoints and then reset if the unit reaches the end of a loop.

And finally, let’s have a little float variable for the speed of our object. I’ve tested it beforehand and this value of 2 seems to work fine for my example but, of course, you might need to adapt this for your own game!

Implementing the patrolling logic

Now, let’s see how to really get the unit moving from one point to another.

There are two ways we could go about this:

  • we could use the Update() method and continuously check to see if we’ve reached the next waypoint. If we have, then we increase our counter, and optionally reset it to the start of the loop. Else if we haven’t reached it, we just move towards it.
  • or we could use coroutines for each segment of the path: basically, whenever we reach a new waypoint, we start a new coroutine to take us to the next, and so on, looping again and again.

This second version is not that much harder to code, though it requires a few additional concepts. Since the “update method version” is enough for our simple use case, I’ll stick with this basic method for the tutorial.

But here is an alternate version of the code that implements the patrolling system with coroutines, so be sure to check it out if you’re interested! 🚀

Ok now – the idea here is to use Unity’s built-in Update() method and check for our distance to the current target waypoint.

If this distance is less than a given threshold, for example here 0.01f, then we’ll consider we’ve reached the waypoint and set the next one as the new target.

What we want to do is first increment our waypoint index by one, but then wrap it back to zero if we overshoot the length of our waypoints array; this can be done using a modulo, in our case with the waypoints array length. This way, as long as the incremented value is below this threshold, it will be left as-is, but if it goes over it, it will be “snapped” back to zero.

Now – if we haven’t reached the waypoint, we have to keep moving in the direction of the current target.

I’ll use the Vector3.MoveTowards() function that allows you to smoothly update a position in a given direction with a specific speed. To insure that the unit speed is independent from the frame rate, we can simply multiply our speed by the Time.deltaTime built-in variable:

All in all, this gives us the following routine for our Update() function:

By the way – here, I’m directly modifying the transform position of my unit object; if you’re using rigidbodies and physics-based logic, you’ll want to use the Rigidbody.MovePosition() method instead and make sure that you write your logic in the FixedUpdate(), rather than the Update().

If you recompile your script and run the game, you’ll see that our unit now goes from one waypoint to the other at a steady speed and, when it’s reach the fourth waypoint, it heads back for the first one.

So here you are – we’ve successfully implemented a very basic waypoint system! 🙂

And remember that a nice thing with us using transforms is that the path adapts to the position of the waypoints dynamically. So if I take one of my waypoints and move it somewhere else, you see that the unit directly updates its current path to get to this new position.

Auto-rotating the unit towards its target

Alright, we now have a simple patrolling routine!

But of course we can still this logic in many ways 😉

For example, it would be nice to also have the unit face its target waypoint while it’s moving. This is pretty straight-forward thanks to Unity’s LookAt() Transform method.

We just have to tell the unit that, if it hasn’t reached the waypoint, it should keep looking at it:

Again, by using Transforms and continuous LookAt()s, we see that if I move the waypoint game object, the unit readapts both its path and its orientation to move towards and keep looking at the target waypoint.

Waiting for a while at each waypoint

One final improvement we can add to our logic is a way for our unit to wait for a while when it reaches a waypoint before moving to the next one. This is often more realistic than just having the enemy speed through its patrol path.

So let’s go back to our script and define a new float variable called _waitTime. This will be the amount in seconds our unit needs to wait for when it reaches the target waypoint. We’ll also need a time counter associated with this variable that I’ll call _waitCounter, and a little boolean flag, _waiting, so that we know if we’re currently in wait mode or not.

Now, in my Update() method, when the distance is small enough and I reach the waypoint, before setting the new index, I want to do a few more things:

  • first, let’s make sure that we are exactly at the waypoint position: we’ll simply assign our position to be the one of the waypoint
  • second, we need to start the waiting routine: we’ll reset the _timeCounter to zero and turn the _waiting flag on

The waiting routine has to happen before our patrolling logic. Basically, if we are in the wait mode – so if the _waiting flag is true –, we want to increase our _waitCounter by the time delta.

Then, if we’re not yet done waiting (meaning that our _waitCounter is less than the _waitTime duration), we need to abort early so that we cancel the patrolling checks.

On the other hand, if our counter has reached the threshold, then we want to exit the wait mode and continue on with our normal patrolling routine.

If I save this and recompile, you see that my unit now stops for a second when it gets to a waypoint before moving to the next one 🙂


That’s it for today folks!

In this tutorial, we implemented a basic patrolling system with adaptive path computation, auto-orientation and optionally additional waits at each waypoint to make a simple but somewhat realistic 3D unit movement.

However, this system only works for simple transforms or rigidbodies: if you want to make a patrolling routine for Unity agents that use the navigation mesh and AI navigation system, you should definitely take a look at the Unity docs and their dedicated short tutorial!

I hope you enjoyed this quick Unity tutorial and the dual video/text versions. Feel free to react in the comments and tell me if you like this format — and of course, go ahead and share your ideas for future topics you’d like me to make Unity tutorials on!

Leave a Reply

Your email address will not be published.