Layer Mask
RAYCASTING | ADVANCED PARAMETERS
Last updated
RAYCASTING | ADVANCED PARAMETERS
Last updated
Layer Mask specifies layers to use in a Physics.Raycast
GameObject can use up t4o 32 Layer Masks supported by the Editor
Layers 0,1,2,4, & 5 are used by Unity by default
Other 24 are controllable by the user
A layer mask is essentially a 32 bit integer
--> Each bit represents an individual layer and defines them as 1 <on/true> or 0 <off/false>
--> Each bit is used to describe whether the layer is used
Unity, by default, uses layers 0, 1, 2, 4, & 5 for
Using a layer mask in correlation with raycasting allows the program only detect certain collisions with your ray.
There are two types of ways we can have the raycast detect whether a layer is on or off when it collides with an object.
To check whether or not a gameobject has a specific layer enabled through the use of its string value we need to follow two steps.
STEP ONE --> Create a variable to store the layerMask's string value
STEP TWO --> Create a Raycast that will detect laymasks through a string value
=>Create a variable to hold the wanted layer <Variable can be serializable for easy modification within Unity's Editor>
LayerMask.GetMask(layerNames) --> returns the layer mask created from the parameter layerNames
=>Create a RayCast that will be able to detect if the gameobject the rayCast collided with has the layer "Enemy" enabled
The above line of code creates a raycast that starts at the position of the attached gameobject and casts a ray 10 units forward. If the raycast hits another collider, the program checks to see whether or not that gameobject has the layer "Enemy" enabled. --> If it does, then the raycast returns true --> If it doesn't, then the raycast returns false
The Downfall to using the string value to check layer masks is because you can only check 1 layer at a time.
To check whether or not a gameobject has a specific layer enabled through the use of its integer value we need to accomplish the following steps.
Check Unity on what the integer value is assigned to the chosen layer.
Create a variable to store the layerMask's integer value
Create a Raycast that will detect layermasks through the use of a bitwise shift operator
=> Check Unity's layer settings to get the integer value of the necessary layers
"Enemy" layer is assigned to int value 6, as shown above.
=> Create a Raycast that will detect layermasks through the use of a bitwise shift operator
The layermask 1 << 6
uses a bitwise shift operator to tell unity to only detect objects who have layermask 6 active.