I can't figure out how OverlapCircleNonAlloc works

Collider2D coversNearby;
Collider2D closestCover;
float closestCoverDistance = 15f;

        int numberOfCovers = Physics2D.OverlapCircleNonAlloc(transform.position, 15f, coversNearby, mask);
        for (int i = 0; i <= numberOfCovers; i++)
        {
            float distanceFromCover = Vector2.Distance(coversNearby*.transform.position, transform.position);*

if (distanceFromCover <= closestCoverDistance)
{
closestCoverDistance = distanceFromCover;
}
}
So what I’m trying to do, is when the player gets detected, the enemy looks for the closest piece of cover available (the closest collider). This is what I have so far, but I’m kinda stuck. In the line where I’m getting the distance between the enemy and X collider, I’m getting a NullRefrenceException (Object reference not set to an instance of an object. Why is this happening, what can/should I do differently? Thanks in advance!

You did not allocate your coversNearby array. The point of the NonAlloc methods are that not Unity allocates a new array each time you call the method, but you allocate it once yourself and reuse it. Keep in mind that you can only get as many results as you have allocated space for. So if you create an array with 5 elements, the method can only fill at max 5 elements, even if there might be 30. So you have to allocate enough elements to hold all the information you care about. Either allocate the array directly in a field initializer

Collider2D[] coversNearby = new Collider2D[10];

or create the array once in Awake or Start.

Another mistake is that you have to use

for (int i = 0; i < numberOfCovers; i++)

instead of

for (int i = 0; i <= numberOfCovers; i++)

If you get one result in your pre allocated array, then “numberOfCovers” will be “1”. So the only valid index you should read is index 0.