2.1 KiB
Bake the navigation
The NavMesh will ignore objects if there if they are not marked with "NavMesh Static" always make sure the objects you want to be treated like obstacles as static, this means that they will not move, this includes the floor.
Open the navigation window which can be found in Window > Ai > Navigation
and once that's opened, go click on Bake
and select "Bake" if there is already baked data (Shouldn't be if this is your first time) go ahead and clear it by clicking "Clear."
Make sure to have the gizmos turned on, as without them, you can't see the navigation path.
Adding the agent to the object
- Add a "NavMesh Agent" to the object you want to have an AI
- Proceed to add a "Script" as well on the same object, call it whatever you'd like
- In your script, add
using UnityEngine.AI
to the dependencies (at the top) - Add a Public transform to your script, call it
target;
- Add a Private NavMesh to your script, call it ``agent'`
- In your start method, set your
agent
toGetComponent<NavMeshAgent>();
- And finally, in your update run the function
destination = target.position
to youragent
.
// You should now have something like this:
using UnityEngine;
using UnityEngine.AI;
public class EnemyMovement : MonoBehaviour
{
public Transform target;
private NavMesh agent;
// Remember: Start runs **AT THE START OF THE GAME** and only once.
void start() {
agent = GetComponent<NavMeshAgent>();
}
// Also remember that this **RUNS EVERY FRAME** remember to use it sparingly.
void update() {
agent.destination = target.position;
}
}
If you want you can also leave the function call in the last step in your start method, unless you want it to run multiple times, say you change the destination.
DON'T FORGET: Make sure you put the target into the object's "Target" field in the inspector!
Avoiding Walls
The following examples will help with avoiding the walls in your AI:
Agent Radius
= The distance your AI should maintain before hitting a wallStep Height
= The size the AI can step up