How to get in enemy to stop after a certain distance from the player?
I can get the enemy to attack and chase but I want to be able to stop the enemy after the player gets a certain distance away from the enemy. I'm new to coding so if it looks like a spaghetti mess I'm sorry. Also extra advice on were to split code or make another script would be good too.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;
public class EnemyController : MonoBehaviour { public float movementSpeed; public GameObject Target; public float lookRadius = 10f; // Attack public int AttackDamageMin; public int AttackDamageMax; public float AttackCooldownTimeMain; public float AttackCooldownTime; public float radius = 3f;
 Transform target;
 NavMeshAgent agent;
   
 void Start()
 {
     target = Player.instance.transform;
     agent = GetComponent<NavMeshAgent>();
 }
 // Update is called once per frame
 void Update()
 {
     float distance = Vector3.Distance(target.position, transform.position);
     if(distance > 10)
     {
         agent.SetDestination(target.position);
         if (distance <= agent.stoppingDistance)
         {
         }
         transform.Translate(Vector3.forward * movementSpeed);
     }
     else
     {
         if (AttackCooldownTime > 0)
         {
             AttackCooldownTime -= Time.deltaTime;
         }
         else
         {
             AttackCooldownTime = AttackCooldownTimeMain;
             AttackTarget();
         }
     }
 }
 void AttackTarget ()
 {
     Target.transform.GetComponent<Player>().TakeDamage(Random.Range(AttackDamageMin, AttackDamageMax));
 }
 void Facetraget ()
 {
     Vector3 direction = (target.position - transform.position).normalized;
     Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
     transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
 }
 void OnDrawGizmosSelected()
 {
     Gizmos.color = Color.red;
     Gizmos.DrawWireSphere(transform.position, lookRadius);
 }
}
Your answer
 
 
             Follow this Question
Related Questions
Enemy AI script for 2D platformer 1 Answer
Enemy Chasing player? 0 Answers
Animations not playing correctly for FPS enemy AI 0 Answers
Detecting Enemy Distance via List 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                