Physics.OverlapSphere object detects itself?

How to prevent a GameObject from detecting itself when using Physics.OverlapSphere?

use the layer part and have what you’re looking for on a separate layer. Here’s how i have mine set up…

random bits of c# code ( a copy and paste of this exactly will NOT compile :stuck_out_tongue:

// first i declared my enemy layer and targets array, i had them public just to see if they were working in inspector...
public int enemyLayer; // Layer enemies are on
public Collider[] possibleTargets;

// in my start function... set enemy layer
enemyLayer = 1 << LayerMask.NameToLayer("Enemy"); // just have to make sure all enemies are on the Enemy layer


// during my detection... or just using overlapsphere...myPos and attackRange should be self explanatory here
possibleTargets = Physics.OverlapSphere(myPos, attackRange, enemyLayer); // only checks enemy layer or so I'm lead to believe...

hope this helps

Thanks Novashot, it makes sense to use the layer mask, but could you explain a little more what you are doing here:

Thanks!

Physics.OverlapShere’s layer mask requires a bit mask.

The line…

LayerMask.NameToLayer("Enemy");

looks for a layer named “Enemy” and returns an int… the number of the layer.

the line:

enemyLayer = 1 << LayerMask.NameToLayer("Enemy");

takes the returned int and bit shifts it… basically turns the int in to a bit mask that physics overlapshere can use.

Thanks Nova, that makes sense, but I still can’t visualise how I can use layermask to have the object not detect itself. The problem is that it is looking for the same GameObjects as itself (ie, “others of its kind”), so any GameObject that I want it to detect will have the exact same layers and tags as the object doing the detecting. Can you see the problem there? I need a “detect any GameObjects the same as me that are not me.”

They do have different names, so I’m trying to do a if(detected.name!=name) but that doesn’t seem to work so well.

EN
ps. Apologies for the consistent delays in reply: notification emails for this thread are not arriving for some reason.

In a case like that, what you can do is temporarily move your game object to the “ignore casting” layer, do the cast, and then restore it’s original layer. Something like:

int oldLayer = gameObject.layer; // This variable now stored our original layer
gameObject.layer = 2; // The game object will now ignore all forms of raycasting

// Do your physics overlap sphere here

gameObject.layer = oldLayer;
5 Likes

Excellent! Thanks Kyle.
EN

Just compare the gameObject. e.g. if (this.gameObject == collider.gameObject) = I hit myself.

2 Likes