I have a pool of 10 enemy objects that get spawned from one of 3 random locations around a central point.
I have towers which target the incoming enemies using OverlapSphere. I’m not using a layer mask at the moment.
After some time running, towers will start picking up enemies which are being spawned far outside of their OverlapSphere range. I’m looking for targets like this:
private void LookForTargets() {
if (targetEnemy != null && !targetEnemy.gameObject.activeInHierarchy) {
Debug.Log($"{name} target {targetEnemy.gameObject.name} is now inactive");
targetEnemy = null;
}
float targetRadius = 5f;
Collider[] colliders = Physics.OverlapSphere(transform.position, targetRadius);
foreach (Collider collider in colliders) {
Enemy potentialTargetEnemy = collider.GetComponent<Enemy>();
if (potentialTargetEnemy != null) {
// Found an enemy.
// Previously pooled objects are getting picked up when they are reactivated
// even though the should have been outside of the target radius.
float distanceToNewEnemy = Vector3.Distance(transform.position, potentialTargetEnemy.transform.position);
if (distanceToNewEnemy > targetRadius) {
Debug.Log($"{name} distance to {potentialTargetEnemy.gameObject.name} = {distanceToNewEnemy}");
continue;
}
if (targetEnemy == null) {
SetTargetEnemy(potentialTargetEnemy);
} else {
float distanceToCurrentEnemy = Vector3.Distance(transform.position, targetEnemy.transform.position);
if (distanceToNewEnemy < distanceToCurrentEnemy) {
SetTargetEnemy(potentialTargetEnemy);
}
}
}
}
}
It can run fine for a period of time, then suddenly one tower or another will start picking up colliders way outside of their range. I set it up so that each spawn point should only be targeted by one set of towers. These two towers finished a wave and then on the next wave that spawned generated the following messages. The specified enemy game object was NOT in the previous wave:
pfArrowTower(Clone)3 distance to pfEnemyMeteorite(Clone)_1 = 32.51066
UnityEngine.Debug:Log (object)
Tower:LookForTargets () (at Assets/Scripts/Tower.cs:62)
Tower:HandleTargetting () (at Assets/Scripts/Tower.cs:39)
Tower:Update () (at Assets/Scripts/Tower.cs:18)
pfArrowTower(Clone)4 distance to pfEnemyMeteorite(Clone)_1 = 30.09656
UnityEngine.Debug:Log (object)
Tower:LookForTargets () (at Assets/Scripts/Tower.cs:62)
Tower:HandleTargetting () (at Assets/Scripts/Tower.cs:39)
Tower:Update () (at Assets/Scripts/Tower.cs:18)
It spawned on the other side of the map and is clearly outside of the radius supplied to OverlapSphere. Why would it get picked up?