1
Answer

problem with moving objects in 2d array

Ask a question
Fred

Fred

15y
6.5k
1

Hi, I'm trying to get some objects to move around in a 2d array of lists, but the program keeps exiting with 'System.InvalidOperationException' and "Additional information: Collection was modified; enumeration operation may not execute."

 

 

I'm pretty sure that this is the part of the code causing all the problems-

 

public void cycleThroughList()

        {

            for (int x = 0; x < GridDimention; x++)

            {

                for (int y = 0; y < GridDimention; y++)

                {

                    foreach (Microbe i in theWorld[x, y])

                    {

                        i.Talk();

                        Update_Position(i);

                        

                    }

                }

            }

        }

 

public void Update_Position (Microbe m)

{

    if (m.sX != 0 & m.sY != 0)

    {

    theWorld[m.positionX, m.positionY].Remove (m);

    theWorld[m.positionX + m.sX, m.positionY + m.sY].Add (m);   

    }

 

    m.Talk();

}

 

Where 'Talk' is a method that writes to the console the coordinates of the Microbe object, and the 'int sX' and 'int sY' are the modifications to the objects location on the array.

 

Do you guys have any idea how to fix this?

I really appreciate any advice you can give me!


Answers (1)