r/UnityHelp • • Aug 22 '22

Raycast in Unity2D

When using a Raycast with Physics2D how do I make it detect only one layer.

[Serialize Field] private LayerMask floor; 
RaycastHit2D hit;
hit = Physics2D.Raycast(transform.position, other.transform.position, floor);

The above is the same code except the point I am using as my Raycasts target is a specific GameObject. The Raycast works, but it always detects the player. I want it to detect only the layer set in the floor variable.

3 Upvotes

2 comments sorted by

1

u/_vert Aug 22 '22

I can't remember how but you use a layer mask

1

u/nulldiver Aug 22 '22

The attribute to serialize a field is SerializeField not Serialize Field - what you have written should be giving you a syntax error and will definitely not work.

Assuming that is just a typo here and it is correct in the script:

  • Have you set the floor LayerMask to just be the layer of your floor in the inspector?

  • Are you sure that the player's colliders are not on that floor layer?

It will work, so the error must be in configuration - you should double check that.

For future reference: By serializing the field, you expose it in the inspector, but you can also set it by code if you want, just for future reference. LayerMasks are bitmasks, so if your "Floor" layer's index is 6, for example, you set the sixth bit: 1 << 6.

So if your layer is named "Floor", you can do something like:floor = 1 << LayerMask.NameToLayer("Floor");

You can also just ask Unity to do it for you, but it is nice to know that it is just a bitmask and you can do normal bitmask stuff with it:floor = LayerMask.GetMask("Floor");