Unity's Layer
Unity uses Int32 to represent 32 layers, and int32 uses binary to represent a total of 32 bits.
0000 0000 0000 0000 0000 0000 0000 0000
31 0
See a few examples to turn on Layer 2
Layermask mask = 1<<2;
The 1 on the left of << indicates that there is [open],0 means no layer[ignored]. The 2 on the right represents the position of the LAYER2 layer by moving the left 2 bits.
Turn on Layer 0 and Layer 2
Layermask mask = 1 << 0 | 1 << 2;
Turn on Layer0 and close Layer2
Layermask mask = 1 << 0 | 0 << 2
Turn on layer Default
Lasermask mask=1 << Laysermask.nametolayer ("Default");
Script examples
Here is a script example that binds it to the camera
Using unityengine;Using system.collections; [requirecomponent (typeof (Camera))]PublicClass Layermasktest:monobehaviour {Open NPC layer, Change to 1 or operatorPrivatevoid Show () {//camera.cullingmask |= 1 << layermask.nametolayer ("Npc"); camera.cullingmask = (int" 1<<layermask.nametolayer (//off NPC layer, Change 0 Bitwise AND & bitwise counter ~ private void Hide () {camera . cullingmask &= ~ (1 << layermask.nametolayer (//switch NPC layer, Bitwise XOR ^ private void Toggle () {camera.cullingmask ^= 1 << layermask.nametolayer (void ongui () {if (guilayout.button (if (guilayout.button ( "hide") hide (); if (guilayout.button ( "Toggle")) Toggle ();}
Real-world Application of Unity collision detection
static bool Raycast (Vector3 origin, Vector3 direction, float distance = mathf.infinity, int layermask = Defaultraycastlaye rs);
Physical collision Mutex
We write our own physical collision mutex in the project
Turn on the NPC layer collision Layermask mask = 1 << (int) gamelayerdef.npc;float bounds = 2; raycasthit2d raycasthit = physics2d.circlecast (transform.position, bounds, vector2.right, mathf.infinity, Mask.value) ;
Information literature
Part of the content is referenced from: "wind yu chong" binary: four Unity
Bitwise operations of the "go" Unity Layermask