- Home /
OverlapSphere ignoring all colliders when I use the layerMask parameter.
When I try to use the layerMask
argument it ignores all layers and doesn't detect any colliders and/or objects. In all the examples I've seen people usually assign an integer the number of the layer and then use it as the right operand of a left bit shift operator on 1, for example: 1 << iLayer
. I don't understand why they do this, there isn't very good documentation on this function or that argument in particular and even after doing the left bit shift it still ignores all colliders/objects in the scene if I try to use the layerMask
parameter. Same if I just put the integer only or try to use the LayerMask.NameToLayer
method. Any suggestions, explanations, documentation, examples, etc would be much appreciated as to why it isn't working and how to properly use this function and or parameter.
using UnityEngine;
using System.Collections;
public class SunGrav : MonoBehaviour {
private Collider[] hitColliders;
void Update () {
hitColliders = Physics.OverlapSphere (transform.position, 20.0f, 8);
for (int i = 0; i < hitColliders.Length; i++) {
Debug.Log (hitColliders [i]);
hitColliders [i].gameObject.SetActive (false);
}
}
}
Answer by meat5000 · Apr 28, 2016 at 07:48 AM
A Layermask is a bitmask. An integer has 32 bits and so in bit form it can represent the on-off state of 32 channels!
The bit shift operator is setting up this mask by taking number 1 (00000000000000000000000000000001 - binary) and shifting (rotating around) the number effectively moving the number 1 to the left (00000000000000000000000010000000 - binary).
Try
int layerMask = 1 << 8; //Layer 8
hitColliders = Physics.OverlapSphere (transform.position, 20.0f, layerMask);
It worked but before I had assumed that this argument specified colliders to be ignored. Does it make the OverlapSphere
pay attention only to that specific collider? It says "A Layer mask that is used to selectively ignore colliders when casting a ray." I took selectively to mean selecting the colliders we want to ignore. I think I know how it works but do you know whether it ignores that layer or only pays attention to it.
It will search only on the selected layer.
You can invert a mask
~(1 << 8) //All but 8
and you can specify multiple layers
(1<<8) || (1<<11) // None but 8 and 11
It is possible to simply use an integer (decimal) value for a layermask but you must work out the decimal equivalent of your binary number. The value of each binary digit moving from right to left is double to digit before. Starting from 1, mark it down on your 32 Zeroes.
http://s32.postimg.org/qt3ojhct1/Binary_Digit_Values.jpg
(Sorry it wont let me post an image at the moment)
Add a 1 to each layer you want to include in your mask (the one on the right is layer 1, then move left). Add the decimal value of each layer together.
Following this process reveals that the value of 8d
as you put in originally actually represents layer 4.