unity-game-enginelayercolliderraycast

Unity Layers overlap and raycast doesn't ignore the one I want


So, I have this code:

if(Input.GetMouseButtonDown(0)){
   ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
   hit = Physics2D.Raycast(ray, Vector2.zero, maskLayer2.value);
   if(hit.collider != null){
      TagName = hit.transform.tag;
   }
}

And I have two different objects with their respective layers: layer1 and layer2, and I want the raycast to detect the object in layer2. The thing is, their colliders overlap and the raycast only detects the collider of layer1 ending up giving the wrong TagName. The only layer in LayerMask is layer2, so I don't know what to do. Does anyone know how to solve this?


Solution

  • The wrong overload of Physics2D.Raycast is being used.

    public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance)
    

    The layerMask is being implicitly converted to a float and used as the distance parameter.

    To fix, include the distance parameter before the layermask in the parameter list.

    Physics2D.Raycast(origin, direction, distance, layerMask)
    

    You can use Mathf.Infinity for distance if you want the raycast distance to be infinite.