Enable or disable specific layer object rendering on runtime in unity3d

 Unity layers are one of the important ways to distinguish between different objects. It helps us to separate or categorize game objects in the scene like a tag. Additionally, you can also use it for collision detection and rendering with the camera.

In this post, we will look at camera rendering with a specific layer. On editor mode, we can render specific layers using the Camera Culling Mask property. 



But sometimes we want to hide or show specific layers of objects on runtime. For this reason, we can use a layerMask. Using layer mask is not straightforward as it required logical operators like AND OR or bitwise operation understanding. So in this post, without considering the depth of this topic, you will learn how to show or hide a specific layer object using camera layerMask.


Hide an object by layer - Removing Layer from layerMask

With the below code snippet, you can hide layer # 8 rendering. The camera will not render objects who belong to layer # 8. If you use this code then, you can make sure that a certain layer should not be rendered by the camera. 

Camera.main.cullingMask &= ~(1 << 8);

You can replace the number 8 with any layer.

Camera.main.cullingMask &= ~(1 << LayerNoToRemove);

 

Show object by layer - Adding a layer in layerMask

If you hide the layer above the code snippet you can do the viceversa. If you want to show a specific layer in addition to other layers that are currently selected in layerMask you can use below code snippet.

Camera.main.cullingMask |=  (1 << 8);

Layer 8 will render along with other layers.


 

Post a Comment

0 Comments