- Home /
Overlap Sphere detecting itself
I have a problem, where my Physics.OverlapSphere is detecting itself, this is a problem, when trying to detect the nearest object, because that will always be itself.
var Closest : Transform;
var hitColliders = Physics.OverlapSphere(transform.position, ViewDistance);
var i = 0;
while (i < hitColliders.Length) {
if (hitColliders[i].gameObject != this.gameObject) { //Why isn't this line preventing it?
Closest = hitColliders[i].transform;
}
}
because probably the script is attached to a child or parent of the object with the collider
well this is weird, try displaying the names of the objects:
Debug.Log("this object: " + this.gameObject.name);
while (i < hitColliders.Length) {
Debug.Log("collider #" + i + ": " + hitColliders.gameObject.name);
if (hitColliders[i].gameObject != this.gameObject) { //Why isn't this line preventing it?
Closest = hitColliders[i].transform;
}
}
Debug.Log("closest: " + Closest.gameObject.name);
i did not use editor so sorry if I have mistakes
Answer by tanoshimi · Dec 24, 2014 at 03:27 PM
OverlapSphere has an optional third parameter that allows you to specify a layer mask. Use it to exclude the layer on which your Player is placed.
The problem is that It has to be able to find others of the same layer/tag.
Why? In that case you'll have to simply loop through all colliders and store value of "closest collider that is not me"
Because it is for an animal AI system, where the animals can be cannibals
I found a solution, to check if the position was the same as the object:
if (hitColliders[i].transform.position != transform.position) {
EP: shorter to just check whether it's you: if(hitColl[i].transform==transform)
Your answer
