c# help fix argument is out of range error

i cant seem to figure out what i did wrong if i drag the targetting script on the character it works but if i start the game with the script pre attached to the player character i get the error

i’m getting this error when i press play and press tab
at any distance

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[UnityEngine.Transform].get_Item (Int32 index) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System.Collections.Generic/List.cs:633)
Targetting.TargetEnemy () (at Assets/_Scripts/Targetting.cs:52)
Targetting.Update () (at Assets/_Scripts/Targetting.cs:85)

targeting script

/// TargetMob.cs
/// Oct 20, 2010
/// Peter Laliberte
/// This script can be attached to any permanent gameobject, and is responsible for allowing the player to target different mobs that are with in range
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Targetting : MonoBehaviour {
public List targets;
public Transform selectedTarget;

private Transform myTransform;
// Use this for initialization
void Start () {
	targets = new List<Transform>();
	selectedTarget = null;
	myTransform = transform;

public void AddAllEnemies() {
	GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
	foreach(GameObject enemy in go)

public void AddTarget(Transform enemy) {

private void SortTargetsByDistance() {
	targets.Sort(delegate(Transform t1, Transform t2) {
			return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));

//if we do not have an enemy targeted ywt, then find the clostest one and target him
//if we do have an enemy targeted, then get the next target
//if we have the last target in the list, then get then first target in the list
private void TargetEnemy() {
	if(selectedTarget == null) {
		selectedTarget = targets[0];
	else {
		int index = targets.IndexOf(selectedTarget);
		if(index < targets.Count - 1) {
		else {
			index = 0;
		selectedTarget = targets[index];

private void SelectTarget() {
	selectedTarget.renderer.material.color = Color.red;
	PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
	pa.target = selectedTarget.gameObject;

private void DeselectTarget() {
	selectedTarget.renderer.material.color = Color.white;
	selectedTarget = null;

// Update is called once per frame
void Update () {


The problem is in line

selectedTarget = targets[0];

It looks like your targets List is empty at that point. You’re filling it in the Start method, but are you sure that any game object with “Enemy” tag is available at this point? Because if there are none, then


line won’t be called. To determine if any enemy object was found, please put

print("enemies found: " + go.Length);

just after

GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");