- Home /
How can I compare Collider's layer to my LayerMask type variable?
Hi!
I have a problem. I have a missile prefab, which instantiates an explosion prebab on destroy. The explosion has a sphere collider. The missiles must ignore the collider of the explosions. I figured out one way to do this, but maybe, I'll need more to ignore later, not only the layer called "explosion". So, I decided to read about LayerMasks and I tried to use them. I failed, and I don't know, what is the problem. Here is a working code, Layer #9 is "explosion".
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.layer != 9)
{
Debug.Log("EXTERMINATE!");
Explode();
}
}
At the variable declaration part, I have a line:
var ignoreLayers : LayerMask;
I want to use this for check for more different layers. If the Collider's layer is not what I selected, explode, otherwise do nothing.
Here is what I tried but didn't work:
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.layer != ignoreLayers.value)
{
Debug.Log("EXTERMINATE!");
Explode();
}
}
If I select explosion layer, it does nothing, it still executes Explode() function and logs "EXTERMINATE".
So, how to use LayerMask.value? I didn't find solution yet.
I dare say I'm missing something, but is there a reason why you're not using Physics settings to prevent the explosions' layer from interacting with the missiles' layer?
Answer by whydoidoit · Mar 22, 2013 at 03:00 PM
LayerMask is a bit flags field so to test it you do this:
if(((1<<other.gameObject.layer) & includeLayers) != 0)
{
//It matched one
}
if(((1<<other.gameObject.layer) & ignoreLayers) == 0)
{
//It wasn't in an ignore layer
}
Answer by churi24 · Aug 15, 2017 at 04:29 PM
This work for me..
public LayerMask layerMask;
private void OnCollisionEnter(Collision collision)
{
if ((layerMask & 1 << collision.gameObject.layer) == 1 << collision.gameObject.layer)
{
Explotar(true);
}
}
And if you have an Editor.cs
using UnityEditorInternal;
[CustomEditor(typeof(Misil))]
public class MisilEditor : Editor
{
Misil misil;
public override void OnInspectorGUI()
{
serializedObject.Update();
misil= (Misil)target;
LayerMask tempMask = EditorGUILayout.MaskField("Mask",InternalEditorUtility.LayerMaskToConcatenatedLayersMask(misil.layerMask), InternalEditorUtility.layers);
misil.layerMask = InternalEditorUtility.ConcatenatedLayersMaskToLayerMask(tempMask);
}
}
Your first code snippet helped me to correctly compare an object layer with a layer mask. The bit pattern nature of these masks has been challenging for me to understand. Thank you!
Your answer
![](https://koobas.hobune.stream/wayback/20220613094903im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiated prefabs not keeping their layers 0 Answers
Problem with OnTriggerEnter 2 Answers
Objects do not destroy on Collision 1 Answer
Trying to detect multiple points on a single collider 1 Answer