Day 74: Working with Unity’s Nav Mesh System for Smart AI
Objective: Use Unity’s NavMesh to move the player.
To start using the NavMesh system we will need to bake the NavMesh. Baking a NavMesh will tell the NavMeshAgent what can be walked on. NavMeshAgent is a component that goes on the player.
To bake a NavMesh, go to Window -> AI -> Navigation.
A Navigation window will come open up normally beside the Inspector. We will need to have our floor selected and in the Navigation window, select Bake at the top and all that’s left is to select bake at the bottom.
Once it finishes baking, all the flat area’s plus the stairs will have a blue overlay on top of it. The blue area is where the AI system will know it can walk.
Now to get the Player working. On the Player object we need to add a NavMeshAgent component.
Now that we have the Player object set up it’s time to set up the logic. In our script we will need to add a new library to our code. At the top of your Player script add “Using UnityEngine.AI;”.
With that added we can now used the variable type NavMeshAgent. We will need to create a variable NavMeshAgent named _playerAgent.
Next will be to use GetComponent to use the get the NavMeshAgent component.
Now it’s time to move the player. After we check to see if we hit something we need to call “_playerAgent.SetDestination(hit.point);”. This moves the object to the location of hit.point.
That’s all there is. Your player will move to where you click!
Thank you for reading and have a wonderful day!