Step 3: Constructing The AI Script
Now that your cylinder is a NavMesh agent, it only needs destinations to start moving. To that end, create a new C# script and name it navigation. We’ll first start by initializing all the variables that will be needed for the script to function. These will make more sense as we utilize them, for now just copy them down.
We have laid the framework for a navigation system that generates random destinations from the total map available and will subsequent destinations after a random interval.
Next you may fill out the Start () function which runs once when the script is activated (usually when the game begins) and retrieve’s the NPC’s own NavMeshAgent component. Following that you may construct the PathGen() function which exists outside of Start() and will be called whenever the NPC needs to generate a new random destination.
Let’s break down the function to understand how it works. A destination can be created in one of five possible general locations, those being the four corners and center of the map. A random x and random y value are pulled from the range of all possible values within the general location selected. A goal object (which you will create shortly) will then have its location set to the generated x and y position. The NavMesh agent then sets its destination to the location of the goal. While it seems convoluted, this has the added benefit of visualizing where our NPC’s are moving to via the goal object. This will be disabled in the actual game view but is useful for debugging and ensuring all NPCs are navigating properly.
The remaining code is displayed here.
The code loop is set on a timer, once it reaches zero PathGen() is triggered and a new timer is set given the minimum and maximum values of the relevant map size variables. Simply picking a random destination from the entire range of the map is avoided because this tends to crowd NPCs into the statistically optimum center.
All that remains are a few finishing touches.