How to Create and Use Layers in Unity

Notes:

How to Create and Use Layers in Unity :
Layers are the way of grouping game objects to control operations like rendering, light illumination, physics interactions, Ray casting etc.

Viewing Tags & Layers Manager:
Edit menu – Project Settings – Tags & Layers
Note: There are 32 layers; first 8 are reserved for specific purpose they are built in layers
and remaining are user layers.

Adding new layer:
Click on Layers - Click on the first empty user layer - Name the layer
Note: Layers can be renamed

Assigning layers:
Select a game object - Click on the Layer drop down menu - Click on the required layer name

Layer dropdown in the tool bar:
Used control which layer objects must be displayed in the scene view or not

Layers are used to control:
Rendering: Which layer objects a camera must render and must not render
Camera - Culling mask - Check/uncheck the layer(s)

Light illumination: Which layer objects must be illuminated by this light and not illuminated
Light - Culling mask - Check/uncheck the layer (s)

Physics Interactions: Which layer objects must interact with which layer objects
Edit- Project Settings - Physics - Uncheck respective checkbox

Ray casting:
Which layer objects must be hit by a Ray and not

using UnityEngine;

//Attach it to camera or player
public class RayCaster : MonoBehaviour {

int layerIndex =0; // Default layer is at 0

void Update () {

int layermask = 1 << layerIndex;

// except objects within the layer index, all other objects must hit by the ray
layermask = ~layermask;

RaycastHit hit;

if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out hit, Mathf.Infinity, layermask)) {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) * hit.distance, Color.green);
} else {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) * 1000, Color.red);
}
}
}