【发布时间】:2021-03-18 07:07:01
【问题描述】:
在我的 Unity 项目中,我有一个 LevelGenerator 创建 Stages(游戏对象)并将这些添加到列表中。当我快死时,我想销毁并删除列表中的所有项目。但是当我遍历列表时,只有第一个对象被销毁和删除,然后发生错误:
InvalidOperationException:集合已修改;枚举操作可能无法执行。
System.ThrowHelper.ThrowInvalidOperationException(System.ExceptionResource 资源)(在:0)
System.Collections.Generic.List1+Enumerator[T].MoveNextRare () (at <fb001e01371b4adca20013e0ac763896>:0) System.Collections.Generic.List1+Enumerator[T].MoveNext () (at :0)
你能帮帮我吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGenerator : MonoBehaviour
{
private const float PLAYER_DISTANCE_SPAWN_LEVEL_PART = 25f;
[SerializeField] private Transform Startingstage;
[SerializeField] private List<Transform> StageList;
[SerializeField] private Transform player;
public List<GameObject> gameObjectsToDestroy;
public bool creatingGoesOn = false;
private Vector3 lastEndPosition;
public void CreateEnviroment() // Every time called when game is started
{
lastEndPosition = Startingstage.Find("EndingPoint").position;
int startingSpawnLevelParts = 7;
for (int i = 0; i < startingSpawnLevelParts; i++)
{
SpawnLevelPart();
}
creatingGoesOn = true;
}
private void Update()
{
if (creatingGoesOn)
{
if (Vector3.Distance(player.position, lastEndPosition) < PLAYER_DISTANCE_SPAWN_LEVEL_PART)
{
// Spawn a new level part if player is to close to the end.
SpawnLevelPart();
}
}
}
private void SpawnLevelPart()
{
Transform randomStage = StageList[Random.Range(0, StageList.Count)];
Transform lastLevelPartTransform = SpawnLevelPart(randomStage, lastEndPosition);
lastEndPosition = lastLevelPartTransform.Find("EndingPoint").position;
}
private Transform SpawnLevelPart(Transform stage, Vector3 spawnPosition)
{
Transform levelPartTransform = Instantiate(stage, spawnPosition, Quaternion.identity);
gameObjectsToDestroy.Add(levelPartTransform.gameObject);
return levelPartTransform;
}
}
错误脚本内部:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.CompareTag("Player"))
{
destroyEnviroment.creatingGoesOn = false;
Debug.Log(destroyEnviroment.gameObjectsToDestroy.Count);
foreach (GameObject toDestroy in destroyEnviroment.gameObjectsToDestroy)
{
destroyEnviroment.gameObjectsToDestroy.Remove(toDestroy);
Destroy(toDestroy); //Somewhere here is the error
Debug.Log(destroyEnviroment.gameObjectsToDestroy.Count);
}
...
}
...
}
【问题讨论】:
-
foreach (GameObject toDestroy in destroyEnviroment.gameObjectsToDestroy.ToList())