Creating a Modular Waypoint System in Unity
Currently, the guards in this third-person stealth game work their way through a series of waypoints (a list of Transforms), and then (once they reach the end) work their way back. I’m storing the current index in a private integer variable (‘_currentTargetIndex’) which I’m either incrementing or decrementing with every waypoint/destination reached (depending on whether a ‘_moveUp’ boolean is true or false).
The code for this could do with some serious tidying-up and optimisation. I prefer not to use the Update method unless it’s absolutely necessary, so would rather use coroutines and while loops to handle some of this logic. Equally, I’m not a big fan of seeing quite so much if-statement nesting, although a lot of this is just to ensure the NavMeshAgent has definitely reached its destination:
The ‘WaitBeforeMoving’ coroutine handles, among other things, changing the _targetReached from true to false after a length of time. This is what prevents the bulk of the code above from running while the guard’s stationary (just to give them some pauses so that they’re not constantly moving up and down the path).
The serialised list of Transforms is what allows us to adjust the waypoints for any guard this script is attached to, allowing us to have, for instance, one guard with 5 waypoints and one guard with only 2. Since we’re not hard-coding or expecting a set number of waypoints (although we would admittedly expect at least two), the script is fairly modular/reusable 😉