I am quite a noob both with programming and programming with C# (I have learned some basic Java before). I am trying to play around with C# in Unity3D, and I have a question:
Is it better to use for-loop instead of foreach iteration to remove any items in an ArrayList?
Both seems to work for me. Foreach produce slightly less coding but the discussions on the Internet seems to be favoring for-loop. Which is better and why?
for-loop version:
public void RemoveUnitFromList(GameObject Unit) {
if (SelectedUnitList.Count > 0) {
for (int i = 0; i < SelectedUnitList.Count; i++) {
GameObject ArrayListUnit = SelectedUnitList[i] as GameObject;
if (ArrayListUnit == Unit) {
SelectedUnitList.RemoveAt(i);
// some other codes
}
}
}
}
foreach version:
public void RemoveUnitFromList(GameObject Unit) {
if (SelectedUnitList.Count > 0) {
foreach (GameObject ArrayListUnit in new ArrayList(SelectedUnitList)) {
if (ArrayListUnit == Unit) {
SelectedUnitList.Remove(ArrayListUnit);
// some other codes
}
}
}
}
Edit:
Either of the code snippets above works fine for me. I only want to study the difference between the two.
However, changing in new ArrayList(SelectedUnitList)
to in SelectedUnitList
did not work:
public void RemoveUnitFromList(GameObject Unit) {
if (SelectedUnitList.Count > 0) {
foreach (GameObject ArrayListUnit in SelectedUnitList) {
if (ArrayListUnit == Unit) {
SelectedUnitList.Remove(ArrayListUnit);
// some other codes
}
}
}
}
Edit2: The above code could produce the following error:
InvalidOperationException: List has changed.
System.Collections.ArrayList+SimpleEnumerator.MoveNext () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections/ArrayList.cs:141)
Mouse3.RemoveUnitFromList (UnityEngine.GameObject Unit) (at Assets/Scripts/Mouse3.cs:216)
Mouse3.Update () (at Assets/Scripts/Mouse3.cs:85)
Let me explains more. The method functions dynamically in game. The SelectedUnitList
is an ArrayList used to collect selected unit in a RTS game. The method removes the deselected units from the ArrayList, so Unit
could be 0, 1 or more.
Edit3 (last time): Thank you all for all the information provided. I think @Seminda in the comments answered my question.