Overlapsphere check returns IndexOutOfRangeException

Hi all,

I have a GameObject that checks if there are certain units around him with an OverlapSphere. It works fine when there is a target within the area, but it throws an IndexOutOfRangeException error when there are no targets. I know the error is thrown because I’m apparently trying to access an empty array, but I thought that I countered that by doing an != null check…

How can I prevent this error?

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

public class CreatureTraits : MonoBehaviour
{
    public float senseRange;

    public Transform currentTarget;

    //layers
    [SerializeField] private LayerMask layermask = (1 << 3);

    public void Update()
    {
        if (!hasTarget)
        {
            Collider [] hitColliders = Physics.OverlapSphere(transform.position, senseRange, layermask);
            
            if (hitColliders != null)
            {
                currentTarget = hitColliders[0].transform;
            }
        }
    }
}

Thanks in advance for any help or advise.

I found the solution:

I changed:

if (hitColliders != null)

Into:

 if (hitColliders.Length >= 1)

I hope this helps people who will run into a similar issue.