Help with Collider Array

Hello,
Practicly I have a gameobject that moves towards another object. I made it with colliders. So, now I have multiple collider of these objects, each with a collider. But my AI is constantly running towards a very specific object in the edge of my map. After capturing that he runs to the other objects. The problem is: the other objects a all WAY closer than the object in that edge. So: how can I get the nearest object with colliderarrays?`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class EnemyMovement : MonoBehaviour
{

UnityEngine.AI.NavMeshAgent myAgent;

public NavMeshAgent agent;

[SerializeField] private float range;

// Update is called once per frame
void Update()
{
    Collider[] colliderArray = Physics.OverlapSphere(transform.position, range );
    foreach (Collider collider in colliderArray)
    {

        if (collider.TryGetComponent<M>(out M city))
        {

            agent.SetDestination(collider.transform.position);

            return;

        
        }

    }
}

}`

To find the nearest object with a collider using a ColliderArray, you can use the Physics.OverlapSphere method to get an array of colliders within a certain range, and then use the Vector3.Distance method to find the distance between each collider and the AI gameobject. You can then use this distance to find the nearest collider and set the AI’s destination to its position.

Here is an example of how you could implement this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class EnemyMovement : MonoBehaviour {

    UnityEngine.AI.NavMeshAgent myAgent;
    public NavMeshAgent agent;
    [SerializeField] private float range;

    // Update is called once per frame
    void Update()
    {
        Collider[] colliderArray = Physics.OverlapSphere(transform.position, range );
        // find the nearest collider
        Collider nearestCollider = null;
        float nearestDistance = float.MaxValue;
        foreach (Collider collider in colliderArray)
        {
            if (collider.TryGetComponent<M>(out M city))
            {
                // find the distance between the collider and the AI gameobject
                float distance = Vector3.Distance(transform.position, collider.transform.position);
                if (distance < nearestDistance)
                {
                    nearestDistance = distance;
                    nearestCollider = collider;
                }
            }
        }
        // set the AI's destination to the position of the nearest collider
        if (nearestCollider != null)
        {
            agent.SetDestination(nearestCollider.transform.position);
        }
    }
}

I hope this helps! Let me know if you have any other questions.

Thanks, it works. I am so happy that there are people like you