Blog

LayerMasks simplified

I love LayerMasks because of their power and ability to filter things. I hate LayerMasks because I can never remember how to properly create them in code. To end this love/hate relationship I finally sat down and made a solution that’s incredibly simple and invaluable for taming LayerMasks. You too can now punch LayerMasks in their confusing face.

//Set a camera to only look at layer 7:
void Awake (){
	//by layer id:
	camera.cullingMask = LayerMaskHelper.OnlyIncluding( 7 );
	
	//or by layer name:
	camera.cullingMask = LayerMaskHelper.OnlyIncluding( LayerMask.NameToLayer("UserInterface") );
}

 

//Set a light to affect layers 4, 8 and 11:
void Awake (){
	//LayerMaskHelper doesn't care if you give them in order
	//by id:
	light.cullingMask = LayerMaskHelper.OnlyIncluding( 4, 11, 8 ); 

	//or by layer names:
	light.cullingMask = LayerMaskHelper.OnlyIncluding( LayerMask.NameToLayer("Landscape"), LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("Enemies") ); 
}

 

//Set a light to affect everything except for layers 5 and 6:
void Awake (){
	//by layer id:
	light.cullingMask = LayerMaskHelper.EverythingBut( 5, 6 );

	//or by layer names:
	light.cullingMask = LayerMaskHelper.EverythingBut( LayerMask.NameToLayer("Landscape"), LayerMask.NameToLayer("Player") );
}

 

//Does this camera's culling mask allow it to look at the target object?:
public GameObject target;
	
void Update(){
	bool isTargetLayerInCullingMask = LayerMaskHelper.ContainsLayer( camera.cullingMask, target.layer );
	string textReplacement = isTargetLayerInCullingMask ? "allows" : "does not allow";
	Debug.Log( "This camera's culling mask " + textReplacement + " it to see the target object." );
}

LayerMaskHelper is now included with my Surge framework:
GET IT IN SURGE!

6 Comments

  1. January 31, 2012

    Ha, I just went through a whole thing with changing layer masks on the fly. Your “helpers” are always welcome! Thanks a lot PixelPlacement!

  2. April 1, 2012

    Great little utility! I’m using it inside Blackreef Pirates! thanks

  3. dewd
    June 5, 2013

    Thank you for this! Really appreciated!

  4. April 2, 2014

    Thank you for this! Useful, Really appreciated!

  5. L3V
    January 28, 2015

    Hey!
    I was just about to write the same thing, but I didn’t want to reinvent the wheel, and here it is 🙂 However, the link to the package doesn’t work anymore. If anyone else needs it, you can get it from here: http://pixelplacement.com/v2/2012/01/31/layermasks-simplified/
    L3V