Time for action – chasing the player
Our next script will control our simple chase AI. Because we are making use of the NavMesh and NavMeshAgent components, we can leave nearly all the difficult portions of pathfinding to Unity:
Again, create a new script. This time name it
ChasePlayer
.The first line for this script simply holds a reference to the NavMeshAgent component that we set up earlier. We need access to this component in order to move the enemy.
public NavMeshAgent agent;
The last segment of code first makes sure that we have our NavMeshAgent reference and then updates our goal destination. It uses the
PlayerPosition
script's variable, that was set up earlier, and theSetDestination
function from the NavMeshAgent. Once we tell the function where to go, the NavMeshAgent component does all the hard work of getting us there. We are updating our goal destination in theFixedUpdate
function because we do not need to update the destination in every frame. Updating too often could cause a...