Unity3D only detect certain layers with Raycast

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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store