Ich versuche, mein Einheitsprojekt zu bauen, aber ich kann nicht, da es ein Problem mit einer foreach-Schleife gibt. Genau darunter ist der Fehlercode, den ich erhalte, aber ich verstehe es nicht. Würde jemand erklären können, was eine mögliche Lösung sein könnte? Oder warum dieser Fehler auftritt?Spiel wird nicht wegen einer Foreach-Schleife in der Liste
InvalidOperationException: Sammlung wurde geändert; Aufzählungsoperation wird möglicherweise nicht ausgeführt. System.Collections.Generic.List`1 + Enumerator [UnityEngine.Vector3] .VerifyState() (unter /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs: 778)
System.Collections.Generic.List`1 + Enumerator [UnityEngine.Vector3] .MoveNext() (bei /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic /List.cs:784)
Player_Movement.Update() (bei Aktiva/Scripts/Spieler/Player_Movement.cs: 46)
Kontext zu geben, Code, den Sie eine Linie auf dem Bildschirm zeichnen zu sein und es erstellt eine Liste von Vektoren für den Spieler t o durchgehen.
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);
}
}
}
}
möglich dup: [so1] (http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) [so2] (http://stackoverflow.com/ questions/2024179/collection-was-modifiziert-enumeration-operation-may-not-execute-in-arraylist) –
Kurz gesagt, Sie sollten keine Liste ändern (zB mit 'Add()') während Sie iterieren mit einer 'foreach' Schleife.Versuchen Sie, Ihre Logik neu zu strukturieren, so dass Sie dies nicht tun müssen. Außerdem ... bin ich mir nicht sicher, ob dein Code das tut, was du denkst. Zur Zeit wird 'nextPosition' zur Liste hinzugefügt für ** jedes ** Element in der Liste, das nicht mit' nextPosition' übereinstimmt, was nicht richtig erscheint. – Serlite