0

I want to check wheither an within a certain radius of the player object is interactable. For this I'm using Physics2D.OverlapCircle to check for 2DColliders near the player. I'm not quite sure why the parameter LayerMask.NameToLayer("Interactable") does not detect anything despite there being objects on that layer. If the 3rd parameter is removed it detects the player as it is the closest

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckInteractable : MonoBehaviour
{
    void Update()
    {
        Collider2D checkRadius = Physics2D.OverlapCircle(transform.position, 5, LayerMask.NameToLayer("Interactable"));       

        if (checkRadius != null)
        {
            print(checkRadius.ToString());        

        }
    }
}

To string is not printed despite there being objects in the interactable layer

  • Just to be sure could you add a [`Gizmos.DrawSphere(transform.position, 5);`](https://docs.unity3d.com/ScriptReference/Gizmos.DrawSphere.html) and see if it really is close enough? (It has to be in `OnDrawGizmos` or `OnDrawGizmosSelected`, not in `Update` ) – derHugo Dec 19 '21 at 14:18
  • 1
    try `1 << LayerMask.NameToLayer("Interactable")` for the last argument – Ruzihm Dec 19 '21 at 16:22
  • Does this answer your question? [Using Layers and Bitmask with Raycast in Unity](https://stackoverflow.com/questions/43559722/using-layers-and-bitmask-with-raycast-in-unity) – Ruzihm Dec 19 '21 at 16:23

3 Answers3

1

I was able to solve the problem. I ended up using the int array version of CircleOverlap. I then set it as a public variable and found that "Use Layer Mask" was set to false, meaning although the mask was set it wasn't active.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckInteractable : MonoBehaviour
{
    public float detectionRadius;

    public ContactFilter2D contactFilter = new ContactFilter2D();

    void Update()
    {
        Collider2D[] results = new Collider2D[5];
        int objectsDetected = Physics2D.OverlapCircle(transform.position, detectionRadius, contactFilter, results);    

        if (objectsDetected > 0)
        {
            print(results[0] + "\t" + results[1] + "\t" + results[2]);
        }
    }
}

Use Mask Layer is now set to true

0

You need to use LayerMask.GetMask()

LayerMask.GetMask("Interactable")
zenonet
  • 325
  • 2
  • 9
0

LayerMask are a bit tricky. The thing returned by LayerMask.NameToLayer returns an index and NOT a layer mask.

You see, layer masks are in fact bit masks and so an index is not the result of a given bit mask. More info here

You may use the LayerMask.GetMask method to create one by code or even add a LayerMask serialized member variable to be able to create the mask in the editor

Hope that helped ;)

Thomas Finet
  • 222
  • 1
  • 6