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
CodePudding user response:
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 ;)
CodePudding user response:
You need to use LayerMask.GetMask()
LayerMask.GetMask("Interactable")