Tutorial: a guard that patrols and chases
An enemy that walks a round and runs at the player when it sees them. It teaches navigation and line of sight.
1. Set up

- Make the guard: a Capsule with a NavAgent component. The level needs ground the agent can walk on; navigation has its own page in Project Settings.
- Make empty objects named
Post 1,Post 2,Post 3... where it should patrol. The script walks them in order. - The player needs the tag
Player.
2. The script

Scripts/Guard.cs
public class Guard : Behaviour
{
public float sight = 12f;
public float chaseSpeed = 5f;
public float walkSpeed = 2f;
GameObject player;
bool chasing;
public override void Start()
{
player = GameObject.FindPlayer();
Round();
}
void Round()
{
var posts = new System.Collections.Generic.List<Vector3>();
for (int n = 1; GameObject.Find("Post " + n) != null; n++) posts.Add(GameObject.Find("Post " + n).transform.position);
gameObject.agent.speed = walkSpeed;
if (posts.Count > 0) gameObject.agent.Patrol(posts.ToArray(), 1.5f);
chasing = false;
}
public override void Update(float deltaTime)
{
if (player == null) return;
Vector3 eyes = transform.position + Vector3.up * 1.6f;
Vector3 them = player.transform.position + Vector3.up * 1f;
// seen: near enough, and nothing but the player on the line between the two
bool near = Vector3.Distance(eyes, them) < sight;
bool seen = near && (!Physics.Linecast(eyes, them, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject) || hit.gameObject == player);
if (seen)
{
chasing = true;
gameObject.agent.speed = chaseSpeed;
gameObject.agent.SetDestination(player.transform.position);
}
else if (chasing && gameObject.agent.arrived)
{
// lost them: back to the round
Round();
}
}
}
Save it as Scripts/Guard.cs and add it to the guard.
3. How it works

Roundcollects every object calledPost 1,Post 2... and tells the agent toPatrolthem, pausing 1.5 seconds at each.- Each frame the guard checks if it can see the player: close enough (
sight) and nothing but the player on the line from its eyes to them (Physics.Linecast). That makes walls hide the player. - Seen: it runs (
chaseSpeed) toward the player. Lost them: when it arrives where it was going, it returns to its round.
4. Try it

Walk behind a wall and the guard loses you. Combine with health: make the guard hurt the player when it touches them.
Next: a turret and its bullets.