UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"advanced ai system"
using UnityEngine; using UnityEngine.AI; public class AdvancedAI : MonoBehaviour { public Transform target; public float detectionRange = 10.0f; public float attackRange = 2.0f; private NavMeshAgent agent; private Animator animator; private bool isAttacking = false; // Start is called before the first frame update void Start() { agent = GetComponent<NavMeshAgent>(); animator = GetComponent<Animator>(); } // Update is called once per frame void Update() { float distanceToTarget = Vector3.Distance(transform.position, target.position); if (distanceToTarget <= detectionRange) { agent.SetDestination(target.position); animator.SetBool("isWalking", true); if (distanceToTarget <= attackRange && !isAttacking) { StartCoroutine(Attack()); } } else { animator.SetBool("isWalking", false); } } private IEnumerator Attack() { isAttacking = true; animator.SetTrigger("attack"); agent.isStopped = true; yield return new WaitForSeconds(animator.GetCurrentAnimatorStateInfo(0).length); agent.isStopped = false; isAttacking = false; } }