overlapsphere to destroy NPCs on exit

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:

  1. 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
  2. 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.
  3. 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);*

}

}

}

  1. If you want to use overlap sphere, you would have to maintain a list of active objects and then check every frame to see if an object in that list did not show up in the next sphere cast. This is definitely not an efficient way to do this.
  2. Yes using OnTriggerExit would be much better as calculating collisions is much less expensive than a spherecast.
  3. If you only have 1 spawn area, then it would be most efficient just to get rid of the large colliders all together and check the distance from each object to the center point of the spawn area