A waypoint is a reference point used for navigation purposes by in-game characters, most commonly used in strategy games and squad based games. They are also commonly used in game design for defining AI paths in nearly every genre. They are a simple concept and an extremely powerful tool.
Today, I’ll go over the ins and outs of setting up a waypoint system in unity.
First, create an empty GameObject. This will need to be saved as a prefab (by dragging it from the hierarchy to the project panel). If you want the player to see it, then create a sphere as a child for it, if not then we can create a gizmo sphere, that will show up in the editor only using:
Gizmos.color = Color.yellow; Gizmos.DrawSphere(transform.position, 1);
This will draw a yellow sphere with 1 unit radius on the transforms’ position, which is really easy to see in the editor, and is great for placing static waypoints for things like enemy AI, or showing invisible areas (this is very useful if you ever roll your own physics)
Now, one waypoint is not usually very useful, and you are probably going to need a list of these, that we move towards and that get deleted once they are reached. A List is what you need. You can fill the list manually in editor or add to it dynamically in-game using List.Add(), up to you. You will need to set your entity to move towards the waypoint that is kept at the start of the list (0), and when it reaches that waypoint, set a local variable to store the waypoint game object, remove that waypoint from the list (List.RemoveAt(0)), and then delete the local variable. this avoids the list from containing a null reference, in case something else tries to access it before you clean up the list.
When you remove a waypoint like this, using RemoveAt(), it will shift all of the items in the list down to fill the empty slot. This means that if your entity is always trying to move towards the first entry, it will now move towards the next waypoint that was in its list, without having to iterate through the list, or needing an int to keep track of its current waypoint, as it will always just move to the first available in the list. Just remember to surround the logic with a check to see if the list has any entries at all. you can achieve this with “if (List.Count() >0)”.
I used this myself in a game I recently made that uses the unity navmesh agent for movement, which just needs a vector3 for its location to head towards, which I will go over in my next blog.