This script makes an enemy move between set points. When the player comes close, the enemy chases the player. Otherwise, it keeps patrolling.
using UnityEngine;
public class EnemyPatrolChase : MonoBehaviour
{
public Transform[] patrolPoints;
public float speed = 2f;
public float chaseSpeed = 4f;
public float chaseRange = 5f;
private int currentPointIndex = 0;
private Transform player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
if (distanceToPlayer < chaseRange)
{
ChasePlayer();
}
else
{
Patrol();
}
}
void Patrol()
{
Transform targetPoint = patrolPoints[currentPointIndex];
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, targetPoint.position) < 0.1f)
{
currentPointIndex = (currentPointIndex + 1) % patrolPoints.Length;
}
}
void ChasePlayer()
{
transform.position = Vector3.MoveTowards(transform.position, player.position, chaseSpeed * Time.deltaTime);
}
}