I need to ‘cast’ the object’s layer, which is the integer shown in the inspector, in to the masked version, which is used to compare with the LayerMask. For example, layer “6” in 1, 2, 3, 4, 5, 6 needs to be 1, 2, 4, 8, 16, 32
Here is a working function to do this:
/// <summary>
/// Checks if a GameObject is in a LayerMask
/// </summary>
/// <param name="obj">GameObject to test</param>
/// <param name="layerMask">LayerMask with all the layers to test against</param>
/// <returns>True if in any of the layers in the LayerMask</returns>
private bool IsInLayerMask(GameObject obj, LayerMask layerMask)
{
// Convert the object's layer to a bitfield for comparison
int objLayerMask = (1 << obj.layer);
if ((layerMask.value & objLayerMask) > 0) // Extra round brackets required!
return true;
else
return false;
}
I learned about extension methods recently and thought I would contribute to this as well.
namespace ExtensionMethods {
public static class LayerMaskExtensions {
public static bool IsInLayerMask(this LayerMask mask, int layer) {
return ((mask.value & (1 << layer)) > 0);
}
public static bool IsInLayerMask(this LayerMask mask, GameObject obj) {
return ((mask.value & (1 << obj.layer)) > 0);
}
}
}
Which can then be used like this:
using UnityEngine;
using ExtensionMethods;
public class LayerMaskTest : MonoBehaviour {
public LayerMask layerMask;
void OnTriggerEnter2D(Collider2D hitObject) {
if ( layerMask.IsInLayerMask(hitObject.gameObject) ) {
Debug.Log(hitObject.name + " is in one of our layers");
}
}
}