2D raycasting with layers in Unity

Daniel Kirwan
2 min readSep 1, 2021

--

Objective: Only detect certain layers with a 2D raycast so you can ignore certain objects

In the video above you should be able to see a green line, and that green line represents the raycast that is happening from the player to determine if they are on the ground layer.

First thing to do is to select your gameobject that you want to detect collisions with on a certain layer. For me, this is a Tilemap object.

Then inside of the script that is controlling the player add in a of serialized fields that you can access inside the editor.

Inside the editor this will give you the option to select the layer that you want the raycast to detect collisions with. For me, I want to detect collision with the ground layer and none other with this raycast.

I am using a 2D raycast.

I am assuming you already know how to use a raycast and only want to know how to detect a certain layer. Inside of the Raycast you need to add the optional parameter of the ground layer. I called mine _ground as shown above and the important thing is to select the value of the ground layer.

Once you do this, the raycast will ignore all collisions on every layer, other than the one you have selected in the inspector.

And that is it, your raycast should ignore all collision that are not on your selected layer.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet