Original Post
I'm using the System.Collection.Stack class in C# to represent a stack of game states. I have a StateManager class which loops through and updates each state in the stack. To test it out, I made "WorldMap" and "MainMenu" states. I gave each state a "hasFocus" variable to determine when to get user input. In my update function for the main menu I want it to remove (pop) itself if it has focus and if the enter key was pressed. This would then give focus to the world map. The problem is when I try and pop the main menu, the enumeration process of "foreach" tells me I can't modify the collection while enumerating. Here's the enumeration: Here's my update function: I'm not able to modify the stack within the enumeration. How should I implement the control and modification of game states in this situation?
using System.Collections;
class StateManager
{
Stack states = new Stack();
public void Update()
{
foreach (GameState item in states)
{
item.Update();
}
}
}
class MainMenu : GameState
{
public override void Update()
{
if (hasFocus)
{
if (Input.Instance.GetKey(Key.BackSpace))
{
StateManager.Instance.Pop();
}
}
}
}

