Edit Camera Culling Mask

Hi, all! Is it possible to change my camera’s culling mask via code? How so?

(I’d like to change it from rendering just one layer, to rendering everything, then back to just the player).

Thanks! -YA

This way you don’t need backup values of old masks:

// Turn on the bit using an OR operation:
private void Show() {
    camera.cullingMask |= 1 << LayerMask.NameToLayer("SomeLayer");
}

// Turn off the bit using an AND operation with the complement of the shifted int:
private void Hide() {
	camera.cullingMask &=  ~(1 << LayerMask.NameToLayer("SomeLayer"));
}

// Toggle the bit using a XOR operation:
private void Toggle() {
	camera.cullingMask ^= 1 << LayerMask.NameToLayer("SomeLayer");
}
int oldMask = camera.cullingMask;

// change mask
camera.cullingMask = (1 << LayerMask.NameToLayer("TransparentFX")) | (1 << LayerMask.NameToLayer("OtherLayer"));
// do something
// ...

// restore mask
camera.cullingMask = oldMask;

Simple visual way:

var playerMask : LayerMask;    // select desired layer in inspector
var everythingMask : LayerMask; // select "Everything" in inspector
..
camera.cullingMask = playerMask;
..
camera.cullingMask = everythingMask;

An easy way to set the culling mask to “Everything” is:

camera.cullingMask = -1; // -1 means "Everything"

-1 is converted to a bit mask having all bits set to 1 (which means all layers).

Camera.main.cullingMask = LayerMask.GetMask(“UI”, “Other”);