I'm trying to build my unity project, however I can't as there is a problem with a foreach loop. Just below is the error code I'm receiving, but I don't understand it. Would anyone be able to explain what a possible a solution might be? Or why this error occurs?
InvalidOperationException: Collection was modified; enumeration operation may not execute. System.Collections.Generic.List`1+Enumerator[UnityEngine.Vector3].VerifyState () (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:778)
System.Collections.Generic.List`1+Enumerator[UnityEngine.Vector3].MoveNext () (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:784)
Player_Movement.Update () (at Assets/Scripts/Player/Player_Movement.cs:46)
To give context to be code you draw a line on the screen and it creates a list of vectors for the player to move through.
void Update()
{
//when the player moves their finger accross the screen of the mouse button is held down
if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) || (Input.GetMouseButton(0)))
{
//raycasthit variable called hit
RaycastHit hit;
//ray variable called ray
Ray ray;
//the ray variable is cast between the main camera and the mouse position
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//if the physics racast hit then calulate the distance betwen the point (mouse position) and the camera
if (Physics.Raycast(ray, out hit))
{
//save the positon as the nextPosition
nextPosition = hit.point;
//save the nextPositions point's yaxis
nextPosition.y = yAxis;
//if there are positions inside of the position list
if (positionList.Count != 0)
{
//then for each vector3 position in the list
Line 46 ===> foreach(Vector3 t in positionList)
{
//if there is no posiiton in the list where one should be
if (nextPosition != t)
{
//then create a position
positionList.Add(nextPosition);
}
}
}
else
{ //otherwise create a position in the position list
positionList.Add(nextPosition);
}
}
}
}