Reputation: 21
In Unity3D i created a zombie character with a simple enemy ai script so that the zombie will chase the player but when i added the NavMeshAgent component it declares the following error message:
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)
I have already tried to bake the NavMesh but it did not work,please help i am stuck. Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UIElements;
public class EnemyAI : MonoBehaviour
{
public float lookRadius = 20f;
Transform target;
NavMeshAgent agent;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
target = PlayerManager.instance.player.transform;
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= lookRadius)
{
agent.SetDestination(target.position);
}
if (distance <= agent.stoppingDistance)
{
FaceTarget();
}
void FaceTarget()
{
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);
}
}
public void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
}
Upvotes: 1
Views: 778
Reputation: 21
Problem solved i just had to check the ground as static and and bake the NavMeshAgent. Hope it helps
Upvotes: 0