Hi, I’m new to overlapshpere and have been using it to activate spawners in the player’s vicinity but I thought I could also use it to destroy NPCs that wander way out of range. I have a population manager script that creates lists of NPCs and has the overlap sphere on it; this is attached to my player.
Some issues I’m running into are:
- how to use overlapsphere to detect if an NPC has left exited the trigger zone, since the list of NPCs is changing all the time and overlapsphere seems dependent on arrays
- how to differentiate between different sphere colliders on the same object. I have two sphere colliders testing for different ranges, I have assigned them to different variables, but I’m having difficulty differentiating between them in the code. I would like to disable mesh renderers if the NPC leaves the closest sphere and destroy if it leaves the larger one to help with performance.
- Is it better to simply use a sphere collider exit instead of overlapsphere to test for exiting NPCs from the list of NPCs?
I appreciate any guidance, general or specific, to help me understand overlapsphere and how to properly implement it.
Here’s the code I have so far, which creates lists and does the overlapsphere activation/deactivation of the spawners:
public class populationmanager : MonoBehaviour
{
//layermasks
public LayerMask spawner, allnpc;
public List<GameObject> allnpcs;
public SphereCollider enablesphere, disablesphere;
Collider[] spawners, npcs;
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<spawner>() != null)
{
ObjectComponentState(other, true);
}
}
private void OnTriggerExit(Collider other)
{
ObjectComponentState(other, false);
if (other.GetComponent<spawner>() != null)
{
other.GetComponent<spawner>().StopAllCoroutines();
}
}
private void ObjectComponentState(Collider other, bool state)
{
if (other.GetComponent<spawner>() != null)
{
other.GetComponent<spawner>().enabled = state;
}
}
private void FixedUpdate()
{
spawners = Physics.OverlapSphere(transform.position, enablesphere.radius, spawner);
for (int i = spawners.Length - 1; i > -1; i--)
{
ObjectComponentState(spawners*, true);*
}
}
}