Why is the Physics2D.OverlapBox not working when i use a layer parameter?

I am studying 2D raycasting, i used a 1x1 square to represent my player and four 1x1 squares to represent the tiles around it(I set all of the tiles to be on a new Layer called Ground), i am currently using this code in the Player GameObject:

void FixedUpdate () {
      
        if (Input.GetKeyDown(KeyCode.D))
        {
            RaycastHits(Vector2.right);
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            RaycastHits(Vector2.left);
        }
        if (Input.GetKeyDown(KeyCode.W))
        {
            RaycastHits(Vector2.up);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            RaycastHits(Vector2.down);
        }
    }

    private void RaycastHits(Vector2 dir)
    {
        Collider2D coll = Physics2D.OverlapBox(dir, new Vector2(1,1), 0, LayerMask.NameToLayer("Ground"));
        Debug.Log(coll);
    }

I am sure it’s a pretty simple mistake but, why is it returning null when i use a layer parameter?

Because you’re passing a layer number to the layer-mask argument. It takes a bit-mask which contain multiple layers whereas Layer.NameToLayer() returns a layer number. To turn a layer number into its bit equivalent then use (1 << layerNumber).

You can also use Layer.GetMask() to do this.

4 Likes