Argument is out of range in array

oksy so I am creating a script to shuffle close targets

here is my code

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

public class Beta_targeting : MonoBehaviour
{
	public Transform selectedTarget;
	public List<Transform> targets;
	
	void Start ()
    {
        targets = new List<Transform>();
	}
	
	public IList<Transform> FindEnemiesInSphere(float radius)
    { 
        Collider[] cols = Physics.OverlapSphere(transform.position, 10);
        SortedList<float, Transform> transforms = new SortedList<float, Transform>();
        foreach (Collider hit in cols) {
            if (hit && hit.tag == "Enemy"){    				
                float Dist = Vector3.Distance(transform.position, hit.transform.position);
                transforms.Add(Dist, hit.transform); 
            }
        }
        foreach(Transform trans in FindEnemiesInSphere(6.0f))
        {
            targets.Add(trans);
        }
        return transforms.Values;
    }

    void Update ()
    {
        if(Input.GetKeyDown(KeyCode.Tab))
            choosingtarget();
    }
    
    public void choosingtarget()
    {
        if(selectedTarget == null) {
            selectedTarget = targets[0];
        }
        else {
            int index = targets.IndexOf(selectedTarget);
            if(index < targets.Count - 1) {
                index++;
            }
            else {
                index = 0;
            }
            selectedTarget = targets[index];
        }
    }	
}

however I get an error

“Argument is out of range.
Parameter name: index”

any help?

The problem is that you never actually assign anything to ‘targets’! Which means that index ‘0’ will be out of range, because targets is empty. You need to have a line in there somewhere which goes like-

targets = FindEnemiesInSphere(radius);

before you try to access any of its members.

Also, what is this line doing in your FindEnemiesInSphere function?

foreach(Transform trans in FindEnemiesInSphere(6.0f))
{
      targets.Add(trans);
}

That really shouldn’t be there. I don’t think you understood what the point of that method was when I wrote it for you earlier.