Working with Layer Mask & Raycast
Limiting the Raycast to certain objects using Layer Mask
In the last article we have learnt that we can separate different game objects with tags and can control whenever the raycast send will affect that certain game object. But that function can only be optimized for limited quantity. An example would be having a FPS game where the player is shooting raycast continuously, it won’t be optimized to have Unity constantly checking game tags. There is where the Layer Mask comes in handy, by sorting objects within Layer mask, unity only checks objects within the desired layer only.
Setting up the Scene:
Since we can use the previous made projects for demonstrate the effects of the Layer mask, not much is required to setup. We will still need a cube platform and some objects on top.
Instead of using tags, this time we are going to use Layer mask, therefore we will need to create a new layer mask name space.
I am then going to assign all the cylinders to the new layer mask.
To update our script (which we have used for the spawning of red spheres) that we currently are using that identifies objects via tags to identify objects with layer mask. We simply need to add onto the IF statement during the Physics condition.
Instead of just ending with “out hitInfo” we are going to add in the “Distance” which we will currently set to Infinity. Then add in the layer mask using Bit Shifting.
Bit Shifting is basically an advance shortcut to turn on layer mask. When I write 1 << 6, the 1 signifies that I want something turned on, by default a 0 is off. Then the 6 is the actual layer which I want to turn on. If for some instance I want to add more layer mask, I can continue to add to the bit shift, I would change the 6 to any other corresponding layer.
Since we are using the same function to Instantiate the red spheres nothing needs to be change. Back into Unity, when we are testing this new script in runtime, we can see that just like before with the tag system, we can instantiate on any object that is under the layer mask “Target”. But since we didn’t assign the platform to the Target layer mask, we aren’t able to instantiate anything.