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

Set up
  1. 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.
  2. Make empty objects named Post 1, Post 2, Post 3... where it should patrol. The script walks them in order.
  3. The player needs the tag Player.

2. The script

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

How it works

4. Try it

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.