收集被修改;即使我没有修改集合,我也可能无法执行枚举操作

时间:2017-11-23 22:21:50

标签: c# foreach

虽然这里有很多类似的问题,但没有一个答案适合我。我得到这个错误并且不知道我做错了什么,因为我没有修改列表我正在循环内部的foreach循环。我只在循环结束后修改列表。代码来自Unity3d脚本,但问题不在于Unity特定的任何内容。

void FindWay(){
    open.Add (new node(myGridLayout.WorldToCell(transform.position)));

    while (open.Count > 0) {

        foreach(node n in open){
            opentmp.Add (n);
        }
        foreach(node n in closed){
            closedtmp.Add (n);
        }
        foreach(node n in open.ToArray()){
            opentmp.Remove (n);
            closedtmp.Add (n);
            Vector3Int tstv;

            if(n.pos==myGridLayout.WorldToCell(target.transform.position)){
                RebuildPath (n);
                break;
            }
            tstv = new Vector3Int (n.pos.x + 1, n.pos.y, n.pos.z);
            if (Walkable (tstv) && !IsClosed (tstv)) {
                opentmp.Add (new node(tstv,n));
            }
            tstv = new Vector3Int (n.pos.x - 1, n.pos.y, n.pos.z);
            if (Walkable (tstv) && !IsClosed (tstv)) {
                opentmp.Add (new node(tstv,n));
            }
            tstv = new Vector3Int (n.pos.x, n.pos.y + 1, n.pos.z);
            if (Walkable (tstv) && !IsClosed (tstv)) {
                opentmp.Add (new node(tstv,n));
            }
            tstv = new Vector3Int (n.pos.x, n.pos.y - 1, n.pos.z);
            if (Walkable (tstv) && !IsClosed (tstv)) {
                opentmp.Add (new node(tstv,n));
            }

        }
        closed = closedtmp;
        open = opentmp;
    }
}

0 个答案:

没有答案