Why do I get an index out of Range error?

using UnityEngine;
using System.Collections.Generic;

[DisallowMultipleComponent]
public class AITargetting : MonoBehaviour
{
AICore core;
List targets;
Transform selectedTarget;
Transform myTransform;

void Start()
{
core = GetComponent();
targets = new List();
selectedTarget = null;
myTransform = transform;
}

void Update()
{
DeselectTarget();
AddAllEnemies();
}

void AddAllEnemies()
{
List enemies;

bool isEnemy = core.faction.Faction == 1;

if (isEnemy)
{
enemies = core.tracker.allies;
}
else
{
enemies = core.tracker.enemies;
}

foreach (Transform enemy in enemies)
{
targets.Add(enemy);
}

TargetEnemy();
}

void TargetEnemy()
{
if (selectedTarget != null)
{
SortTargetByDistance();

int index = targets.IndexOf(selectedTarget);

if (index < targets.Count - 1)
{
index++;
}
else
{
index = 0;
}
}
else
{
SortTargetByDistance();
}
}

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

SelectTarget();
}

void SelectTarget()
{
selectedTarget = targets[0];
core.logic.aiTarget = selectedTarget.transform;
}

void DeselectTarget()
{
if (selectedTarget != null)
{
selectedTarget = null;
targets.Clear();
}
}
}

Hello,

please use code tags to make your code easier to read, also the line of the error would be nice, because you have multiple lists.

Just a guessing, because it´s hard to say anything without the error message: You clear your targets list in “DeselectTarget()”, do you try afterwards to get index[0] from it in “SelectTarget()” on any script ?

1 Like

well it only happens on start… basicly the script works like this all enemies and allies assign themselve to a list on the GameController. They fetch their opponent list addAllEnemies… and selects the closest one in that list. I think the DeselectTarget(), is the cause… but I did if (selectedTarget != null)… so…

I also write my scripts in such a way that I dont get anything from other scripts the scripts assign their own variable… hence:
selectedTarget = targets[0];
core.logic.aiTarget = selectedTarget.transform;

But this line:

selectedTarget = targets[0];

will throw an index out of range exception when the targets list is empty. You can not access element 0 if there is no element at all.

`so can I not say something like if (!targets.empty){
selectedTarget = targets[0];
}
you get that? also: I think this might work. I dont know how to implement it

  • for (int i = 0; i < yourArray.Length ; i++)
  • {
  • // your code.
  • }

you are right selectedTarget = targets[0]; how would you fix this?

Just check if your List is empty and bail-out before that line runs.
if (targets.Count==0) return;

1 Like

The most simple code is usually the best answer thanks.