How to use layers in Unity?
Some time we need to assign objects to the same group so we can apply the same actions or effects to them or instead, prevent them from receiving these actions or effects. For this purpose, layers are commonly used by Cameras to render only a part of the scene, and by Lights to illuminate only parts of the scene. They can also be used by raycasting to selectively ignore colliders or to create collisions.
Creating Layers
To create a new layer, open the “Tags and Layers” window (Edit -> Project Settings -> Tags and Layers category).
Choose one of the empty “User Layers” and write the name of your layer.
You can also create a new layer by clicking on the “Layers” box above the inspector window and choose “Edit Layers”.
Assigning Layers
After creating the new layer, you will assign some gameObjects to it. Select these gameObjects and click on the “Layer” drop-down list box then check the name of the layer that you have created.
Using Layers
a- Using the Camera’s culling mask to draw only a part of the Scene
Using the camera’s culling mask, you can selectively render objects which are in one particular layer. To do this, follow these steps:
1- Select a camera;
2- In the inspector window check or uncheck layers in the “culling mask” property;
In the next screenshots, the Cube gameObject is assigned to “Default” layer and the Capsule gameObject is assigned to “MyLayer 01” layer. So if we check “MyLayer 01” and uncheck all the other layers in the “culling mask” property of the selected camera, only the Capsule gameObject will be visible (rendered) in the “Game” view and at runtime in this camera view.
Note that UI elements aren’t culled. Screen space canvas children do not respect the camera’s culling mask.
b- Casting Rays Selectively
Using layers you can cast rays and ignore colliders in specific layers. For example you might want to cast a ray only against the “MyLayer 01” layer and ignore all other colliders.
The “Physics.Raycast” function takes a layerMask, where each bit determines if a layer will be ignored or not. The layerMask represent the 32 Layers of Unity and define them as true or false.
// Check for “MyLayer 01” layer
LayerMask mask = LayerMask.GetMask("MyLayer 01");
// Does the ray intersect any objects which are in the “MyLayer 01” layer.
if (Physics.Raycast(transform.position, Vector3.forward, Mathf.Infinity, mask))
{
Debug.Log("The ray hits a gameObject in the layer named ‘MyLayer 01’ ”);
}