I'm very new to Unity so please excuse my question if this sounds very basic to you.

I'm following various tutorials and I have a small question regarding Physics.Raycast:

if (Input.GetButton("Fire1")) {
        // check ground hit first
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, LayerMask.GetMask("Ground"))) {
            Debug.Log("[PlayerMotion]: Hit" + hit.collider.name + " " + hit.point);

Here, even tough I expressively set the layer mask to "Ground", I still get a hit with the Player game object itself (the ground hit is working fine). I thought ok maybe I put the "Ground" layer as well on the player by mistake but I checked several times and it's not the case.

I'm attaching a gif so you can see what's the issue exactly

enter image description here

There's an easy by checking the collider.name but I still find it odd that the Raycast gives me a false positive with the player hit. Any idea what's going on ?


1 Answer 1


Make sure you are not passing your layer mask into the maxDistance param.

The signature of Physics.Raycast (the one that accepts a ray as the first argument) is

public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

Notice that the third parameter is maxDistance and not layerMask. In other words, use

Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.GetMask("Ground"))

instead of

Physics.Raycast(ray, out hit, LayerMask.GetMask("Ground"))

This is a common mistake as LayerMask.GetMask returns an int which will be implicitly cast into a float and thrown into maxDistance instead of layerMask.


Not the answer you're looking for? Browse other questions tagged .