- Home /
Removing the last element in an ArrayList; C#
I'm in the process of making an RTS, so I'm coding a basic system to make a block move around the gamespace and whatnot, including the ability to chain commands, as is a staple in RTS. I figured doing this in an ArrayList would be the most straightforward, with each shift-click adding an element to the array and the unit deals with the elements in the array one by one. This works fine except for when the element it's iterating through is the last one in the ArrayList, in which case I get the error "ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count" and the last part of the code isn't executed. Any ideas of what's going wrong or how to fix it? Here's my code:
IEnumerator AccelerateTo () {
//nextDest is my arraylist, in case it weren't obvious
while (nextDest[0] != null) {
Vector3 target = (Vector3)nextDest[0];
Vector3 modifiedTarget = new Vector3 (target.x, 0, target.z);
while (Vector3.Distance (transform.position, modifiedTarget) > .01f) {
//the unit moves, not really streamlined or pretty so left out for the sake of brevity
yield return null;
}
Debug.Log ("Removing " + nextDest[0]);
nextDest.RemoveAt (0);
Debug.Log ("Moving to " + nextDest[0]);
}
GetComponent<Rigidbody> ().velocity = new Vector3 (0, 0, 0);
Debug.Log ("Finished moving");
yield return null;
Answer by Landern · Mar 18, 2015 at 12:49 PM
You're removing while going through a assumed index 0. You should check the count.
while (nextDest != null && nextDest.Count > 0 && nextDest[0] != null)
You also should look into using List's instead of ArrayList which has been deprecated and retired from .net for a while and isn't type safe since you can stuff whatever you want in it during runtime.