Why does Physics.OverlapSphere not always return the same number of colliders?
I have been working on a detection system for characters. I have adopted the reccomended method of using Physics.OverlapSphere to gather an array of colliders that are asigned to a specific layer mask. (Not 8 as I know this can cause issues.)
This is done within a method called from a coroutine, which is delayed to run every 0.2 seconds. The coroutine then does various comparisons to see what was present in the last cycle to determine characters that are new/have left the radius, this was where I first noticed the issue as I was raising more events than I should be, figured it was my logic, on further debugging turned out to be the overlapSphere.
public Collider[] GetRadiusColliders() {
Collider[] characterCollidersinRadius = Physics.OverlapSphere(transform.position, viewRadius, characterMask);
Debug.Log("Colliders found : " + characterCollidersinRadius.Length);
return characterCollidersinRadius;
}
The issue is that the array can contain varying numbers of colliders, even if no positions within the scene change, which is not the expected behaviour. The Debug.Log highlights this.
Any help would be appreciated, likely just a gotcha...
Things I have already tried:
Disabling rigidbody sleep using sleepThreshold = 0.0f on all characters in the scene.
Reducing/increasing the frequency that the method runs.
Running the method in both update and fixed update
Added colliders to all objects, set them to Convex, non-convex.
Increased/ decreased the amount of characters in the scene.
Removed the layerMask and filtered returned colliders.
Used Collider provided by character controller and also added a mesh collider.
Sacrificed first born child to satan.
Thanks
Jack
Answer by Payce · Jul 03, 2021 at 10:04 AM
Turns out the issue was rather simple. I had added RigidBodies to the characters in my scene but not the player, Upon doing so and setting the Rigidbody to Kinematic, the issue was resolved.
Upon some further investigation it turns out that the Animator was slightly modifying the Transform.Position of the player, which was causing the issue (modifying the transform is a no-no as I have recently learned). Some further research pointed out that it is common practice to have a kinematic Rigidbody on a character that is controlled by an animator.
Hope this helps anyone esle who comes across this issue.
J
Your answer
![](https://koobas.hobune.stream/wayback/20220613035207im_/https://answers.unity.com/themes/thub/images/avi.jpg)