OverlapCircleAll always returns an empty array
Hopefully this will be a stupid mistake.
I'm trying to make a weapon pickup system for a 2D game, here is the code.
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
// we get an array of weapons close to the player
Collider2D[] weapons = Physics2D.OverlapCircleAll(this.transform.position, 100f, LayerMask.NameToLayer("Items"));
// if at least 1 weapon was close
if (weapons.Length > 0)
{
...
}
else
{
Debug.Log("No weapons nearby");
}
}
}
What I basically want to do is to get the closest weapon to the player and then equip it, what instead happens is that "No weapons nearby" always gets printed out, no matter how close to the weapons the player is.
Here is a screenshot of the inspector showing that the weapon is in the "Items" layer.
These weapons I'm trying to get all have a BoxCollider2D attached.
Do not hesitate to ask me about additional details, many thanks in advance to everyone coming up with suggestions!
Answer by Larry-Dietz · Jan 29, 2020 at 09:38 PM
If you remove the layermask, and look across all layers, does it return the weapons then? Give this s shot to see if you are just dealing with a layer mask problem. I realize that you are showing that the items are on the expected layer, I am just trying to see for sure where the problem lies.
-Larry
I removed the Layer$$anonymous$$ask and added a foreach after the if statement like this:
if (weapons.Length > 0)
{
foreach (Collider2D item in weapons)
{
Debug.Log(item.ToString());
}
I'm happy to say that the weapons got printed along with enemies, wall tiles and the player. At this point I must be doing something wrong when specifying the layer, although I don't know what.
This is the way I would normally do something like this. Give it a shot, and see if it works for you.
public Layer$$anonymous$$ask WeaponsLayer;
void Update()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
// we get an array of weapons close to the player
Collider2D[] weapons = Physics2D.OverlapCircleAll(this.transform.position, 100f, WeaponsLayer);
// if at least 1 weapon was close
if (weapons.Length > 0)
{
...
}
else
{
Debug.Log("No weapons nearby");
}
}
}
Then select the correct layer in the inspector.
This works perfectly, honestly feels like I should have been able to think about creating a variable for the Layer$$anonymous$$ask. Thanks so much for the help!