Cycling through a List with constantly changing element count. Running into problems D:

Hi,

I’ve basically got this little script that is supposed to cycle through enemies whenever I press the shift key.
It does this, but since the List used to store the enemies keeps changing in size rather fast.

A simple counter runs into index out of range errors, seemingly because when the list would be filled like this: element 0=A, 1=B, 2=C And have enemy C selected, enemy A can suddenly drop out of the list.

Making the list count 2, while I’m trying to select the third, now non existing element. I believe this is the reason why I keep getting these errors, but I’ll post a snippet anyway.

function switchLockOnTarget()
{
	if(Input.GetKeyDown(KeyCode.LeftShift))
	{
		
		if(curLockOn+1>=lockOnTargets.Count)
		{
			curLockOn = 0;
		}
		else if(curLockOn+1<=lockOnTargets.Count)
		{
			curLockOn = curLockOn+1;
		}
	}
}

Am I missing something simple here, or do I need to consider using different methods of cycling through the list?

Thanks in advance,

~Nick

If you have an index to an item in a list, it would make sense to signal when you modify that list.

In the scenario where an item was removed from the list, any indices that reference a greater index should be decremented by one to maintain the correct index.

Perhaps something like this? There may be typos, I just wrote some code without checking that it compiles.

function RemoveItem(index : int) {
   lockOnTargets.RemoveAt(index);
   if (curLockOn == index) {
      // The target was lost, what should we do now?
   }
   else if (index < curLockOn) {
      // Adjust for items removed "below" us.
      curLockOn--;
   } 
}

I would suggest to use a LinkedList instead and hold a reference to the node object that is currently selected. That way the order / count can change without breaking the reference to the “next” item. Of course if the payload object (your gameobject) gets destroyed you should select the next / prev element.

I’ve never tried this myself, but i think it should work.