Reputation: 3
I'm working on a script where the player can toggle between certain objects. If the player touches the object then it is destroyed. I have all the objects in a list that update every second to check if something leaves or is added to said list. I'm having problems dealing out of range errors at the moment and was wondering if anyone could help. How do I properly check to see if index item in list is null or invalid without the error messages?
Here's the error:
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index System.Collections.Generic.List`1[UnityEngine.GameObject].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633) TargetEnemy.SwitchTarget () (at Assets/TargetEnemy.cs:39) TargetEnemy.Update () (at Assets/TargetEnemy.cs:33)
Here's my script:
public int selectableTargets;
public int currentTarget;
public Rigidbody rb;
public bool lockedOn;
void Start ()
{
selectableTargets = LocateEnemy.enemyCount;
currentTarget = 500;
rb = GetComponent<Rigidbody>();
lockedOn = false;
}
// Update is called once per frame
void Update ()
{
selectableTargets = LocateEnemy.enemyCount;
if (currentTarget > selectableTargets || currentTarget < 0)
{
print("I cant find it");
}
else
SwitchTarget();
}
void SwitchTarget()
{
if(LocateEnemy.myTargets[currentTarget].gameObject != null)
rb.transform.LookAt(LocateEnemy.myTargets[currentTarget].gameObject.transform);
}
Upvotes: 0
Views: 599
Reputation: 12258
In your Update()
method, you're checking the value of currentTarget
to ensure it isn't an invalid index for LocateEnemy.myTargets[]
. However, one of your conditions is incorrect: currentTarget > selectableTargets
. This causes currentTarget
to occasionally supply an out-of-range index.
Because arrays are 0-based, you need to remember that valid indices will lie in the range of [0, length - 1]. As such, when you're validating indices for the array, the maximum allowable index should be one less than the length of the array. Updating your code accordingly:
void Update ()
{
selectableTargets = LocateEnemy.enemyCount;
if (currentTarget >= selectableTargets || currentTarget < 0)
{
print("I cant find it");
}
else
SwitchTarget();
}
Note: You can interchangeably use currentTarget >= selectableTargets
or currentTarget > selectableTargets - 1
here because we're using integers, so just write whichever conveys the meaning more clearly to you.
Upvotes: 1