Error “SetDestination” can only be called on an active agent that has been placed on a NavMesh. UnityEngine.AI.NavMeshAgent:SetDestination(Vector3) Enemy_Controller:Update() (at Assets/Scripts/Enemy/Enemy_Controller.cs:28)
I have put the enemy controller script first and the enemy spawner second.
This Is My Enemy Controller Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Enemy_Controller : MonoBehaviour
{
public float lookradius = 10f;
Transform target;
NavMeshAgent agent;
// Use this for initialization
void Start()
{
target = PlayerManager.instance.player.transform;
agent = GetComponent<NavMeshAgent>();
}
// 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)
{
//atack target
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);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookradius);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
public GameObject spawn;
public bool stopSpawning = false;
public float spawnTime;
public float spawnDelay;
// Use this for initialization
void Start () {
InvokeRepeating("SpawnObject", spawnTime, spawnDelay);
}
public void SpawnObject()
{
Instantiate(spawn, transform.position, transform.rotation);
if (stopSpawning)
{
CancelInvoke("SpawnObject");
}
}
}