Unity3D only detect certain layers with Raycast

Daniel Kirwan
2 min readOct 11, 2021

--

Objective: Have the RayCast from the player only detect a certain layer.

I have a RayCast firing from the centre of the screen which is where the player is looking. On my enemy I have two colliders, one is a sphere collider which is a trigger and a character controller which comes with its own collider.

I want my RayCast to ignore the trigger or more importantly, I want the RayCast to only detect objects on a certain layer.

This is pretty easy to do. In your script that is responsible for your RayCast you need to add in a layer to the RayCast. The layer that you add, should be the Layer that you want to detect collisions on. For me, I created two new layers, one for the attackTrigger and one for the enemy.

I exposed the LayerMask as a serializedField so that I can change it in the Unity editor. I need to add a distance for the RayCast to it along with the layer.

Now, in the Unity editor, select the Layer that you want to detect collisions on and the update the game object with the correct layer.

And that is it for detecting collisions in Unity 3D on a certain layer.

If you found this helpful, don’t forget to clap and follow for more articles on game development in Unity.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet