4

I am trying to get all objects within a distance of the current object. the maxShootDistance is set to 3, and when an object that is part of the ShootAt layer gets near/in the circle, it is never picked up, and my debug outputs 0. Why isn't it picking up the other object?

public class QuckShot : Gun {

    void Start () {
        StartCoroutine(shoot());
    }

    IEnumerator shoot(){
        while(true){
            Collider2D[] hitColliders = Physics2D.OverlapCircleAll(transform.position, maxShootDistance, LayerMask.NameToLayer("ShootAt"));
            Debug.Log(hitColliders.Length); // This is always returning zero
            /*
             * Snipped other bits of code
             */
            yield return new WaitForSeconds(shootSpeed);
        }
    }
}

Here are the properties that are assigned to the object that should have been picked up:

Female Properties

Why isn't my code picking up the object?

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

5

This call:

LayerMask.NameToLayer("ShootAt")

NameToLayer returns a layer index (ie: 7), but OverlapCircleAll expects a bitwise layer mask (ie: 7th bit enabled).

In some circumstances, this sort of thing may appear to work, if the layer index happens to have a bit or two in common with the desired layer mask. Either way, it'll get unintuitive and mixed results at best.

You can construct a layer mask using the bitwise left shift operator:

1 << LayerMask.NameToLayer("ShootAt");

(You can add additional layers using bitwise OR.)

rutter
  • 11,242
  • 1
  • 30
  • 46