Find closest string in array and remove the object from the aray

I think I am missing something obvious but my goal is to find the closest object (which works correctly) and then remove it from my ItemType Array. Please refer to the second for loop.

Thanks in advance!!

    private string FindClosestGroup(string[] ItemType, Transform StartPoint)
    {
        GameObject[] candidates = ArrayCreation(ItemType, StartPoint);
        float minDistance = Mathf.Infinity;
        GameObject closest;
        int i = 0;
        if (candidates.Length == 0)
            return null;
        closest = candidates[0];
        for (i = 1; i < candidates.Length; ++i)
        {
            float distance = (candidates[i].transform.position - StartPoint.position).sqrMagnitude;
            if (distance < minDistance)
            {
                closest = candidates[i];
                minDistance = distance;
                              
                for (int x = i; x < itemTypes.Length - i; x++) // i want this to remove the closest tag from the list of arrays
                {                
                    itemTypes[x] = itemTypes[x + 1];
                }
            }
        }
       return closest.tag; // returns closest tag
    }

Arrays do not allow to remove object easily. That’s what List<> is for. List uses an array internally too but has some code for housekeeping. You could “fake” your functionality by copying the last valid index over your index to delete and reduce a validcount variable. But when you have to ask such questions and don’t understand the implications that probably leads to errors and bugs. So my suggestion is to use a List<>.RemoveAt instead.

As for your algorithm. Your if (distance < minDistance) is within the iteration to find the closest. This is bad since you can’t know which is closest until you have iterated over all of them. So during iteration just store the index of the closest and after finishing iteration delete the entry at this index.

This was very helpful. Thanks. I think a list will be much better since it’s dynamic.

For storing the index do you mean making

closest = candidates[i];

Into something like

Int indexToRemove = [i]

?

It should be int (lowercase). Also it must be defined outside of the loop otherwise it gets “overwritten” with each iteration and cannot be accessed outside the loop body. Inside the loop you check for the closest. And after the loop (all objects checked which is closest) you delete the object at the index position.