Unity2D enemy ai patrolling and chasing the player when they come to close.

Hi, I’m having trouble making my enemy break patrol and chase after the player when they’re close but return to their patrol when the player is not within distance. My patrol script deactivates when my chase script is active but I can’t figure out how to make my chase script do the same using the player’s distance as an off switch. It just starts out active and never deactivates. I’ll be grateful for any help that you can provide.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chase : MonoBehaviour
{
    public Transform player;
    public float moveSpeed = 3;
    public float playerDistance;
   

    void Start()
    {
        player = GameObject.FindWithTag("Player").transform;
        playerDistance = Vector2.Distance(player.transform.position, player.transform.position);
    }

    void Update()
    {
        if (playerDistance <= 10.0f)
        {
            ChasePlayer();
        }
    }

    void ChasePlayer()
    {
        playerDistance = moveSpeed * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, new Vector2(player.position.x, transform.position.y), moveSpeed * Time.deltaTime);
    }
}

Without all the code it is difficult to say, but I know that if your patrol script is supposed to regain control and you have disabled it, it no longer runs.

In that case you might need to split things up into a three different parts:

  • patrol script
  • chase script
  • master brain script

The master brain script would be what studies conditions and decides whether to patrol or chase.

This is my patrol script though I mostly want to fix the always running chase script. Are there any tutorials that you can recommend? I’m kind of new to scripting in general.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Patrol2 : MonoBehaviour
{
    public float speed;
    private float waitTime;
    public float startWaitTime;

    public Transform[] patrolPoints;
    private int randomSpot;

    // Start is called before the first frame update
    void Start()
    {
        waitTime = startWaitTime;
        randomSpot = Random.Range(0, patrolPoints.Length);
    }

    // Update is called once per frame
    void Update()
    {
        if (GetComponent<Chase>().enabled == false)
        {
            transform.position = Vector2.MoveTowards(transform.position, patrolPoints[randomSpot].position, speed * Time.deltaTime);

            if (Vector2.Distance(transform.position, patrolPoints[randomSpot].position) < 0.2f)
            {
                if (waitTime <= 0)
                {
                    randomSpot = Random.Range(0, patrolPoints.Length);
                    waitTime = startWaitTime;
                }
                else
                {
                    waitTime -= Time.deltaTime;
                }
            }
        }
    }
}