简体   繁体   中英

Hey,i got a error while making an enemy ai in unity

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);
    }
}

Problem solved i just had to check the ground as static and and bake the NavMeshAgent. Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM