Hi, I need some guidance from the community.
I’ve made a scenario where an NPC will spawn from the spawn point and move towards the exit with the help of NavMesh. I got the spawning and the path-finding to work however I’m unable to destroy the game object when it reaches the exit. A screenshot is as attached:
Here are the codes I’ve used in this scene:
Spawning Script
public class NPC_Spawner : MonoBehaviour
{
public GameObject npc;
public GameObject exit;
void Start ()
{
Invoke("SpawnNPC", 2);
}
public void SpawnNPC ()
{
GameObject na = (GameObject) Instantiate(npc, this.transform.position, Quaternion.identity);
na.GetComponent<NPC_Behaviour>().exit = exit.transform;
// if (na.transform.position == exit.transform.position)
// {
// Destroy(na);
// Debug.Log("Collision Detected!!!");
// }
Invoke("SpawnNPC", Random.Range(2,5));
}
}
NPC Behaviour Script
using UnityEngine;
using UnityEngine.AI;
public class NPC_Behaviour : MonoBehaviour
{
public Transform exit;
void Start()
{
UnityEngine.AI.NavMeshAgent agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
agent.destination = exit.position;
}
}
Exit Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC_Exit : MonoBehaviour
{
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "NPC")
{
Debug.Log("Collision Detected");
Destroy(col.gameObject);
}
}
}
The box collider for exit is set ‘Is Trigger’.
Please let me know what I did wrong here. Your help is much appreciated.