hello I have a problem with my ai system he is not moving at all or doing anything and I have a navmesh surface in my game what can I do? pls help me
here is the code:
using UnityEngine;
using UnityEngine.AI;
public class AIController : MonoBehaviour
{
public NavMeshAgent agent;
public Transform player;
public GameObject projectile;
public LayerMask whatIsGround, whatIsPlayer;
public Vector3 walkPoint;
public float walkPointRange;
public float timeBetweenAttacks;
public float sightRange, attackRange;
public float health;
public bool playerInSightRange, playerInAttackRange;
private bool walkPointSet;
private bool alreadyAttacked;
private void Awake()
{
player = GameObject.Find("PlayerManager").transform;
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
Debug.DrawRay(transform.position + transform.up / 4.5f, transform.forward * 5, Color.green, 2f, false);
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange) Patroling();
if (playerInSightRange && !playerInAttackRange) ChasePlayer();
if (playerInAttackRange && playerInSightRange) AttackPlayer();
}
private void Patroling()
{
if (!walkPointSet) SearchWalkPoint();
if (walkPointSet)
agent.SetDestination(walkPoint);
Vector3 distanceToWalkPoint = transform.position - walkPoint;
if (distanceToWalkPoint.magnitude < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
{
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint, -transform.up, -2, whatIsGround))
walkPointSet = true;
}
private void ChasePlayer()
{
agent.SetDestination(player.position);
}
private void AttackPlayer()
{
agent.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
rb.AddForce(transform.up * 32f, ForceMode.Impulse);
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0) Invoke(nameof(DestroyEnemy), .5f);
}
private void DestroyEnemy()
{
Destroy(gameObject);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(transform.position, sightRange);
}
}