遍历 Vector3 的列表并查看它是否是另一个 vector3 并将其从列表中删除

Loop through a list of Vector3's and see if it is another vector3 and remove it from the list

所以我有一个 Vector3 的列表,我想遍历它并查看它是否等于另一个 Vector3。
我试过这样做,但行不通,我收到一条错误消息
索引超出范围。必须为非负数且小于集合的大小。

这是我的代码:

int n = GameManager.instance.blocks.Count;
                while (n > 1) 
                {
                    if (GameManager.instance.blocks[n] == new Vector3(Mathf.RoundToInt(this.transform.position.x), Mathf.RoundToInt(this.transform.position.y), 0))
                    {
                        GameManager.instance.blocks.Remove(new Vector3(Mathf.RoundToInt(this.transform.position.x), Mathf.RoundToInt(this.transform.position.y), 0));
                    }
                    n--;
                }

但是我得到了前面提到的错误,我要在这里更改什么?

谢谢

您不应该在 Unity 中使用“while”循环。

Vector3 vectorToRemove = new Vector3(Mathf.RoundToInt(this.transform.position.x), Mathf.RoundToInt(this.transform.position.y), 0);

for(int i = GameManager.instance.blocks.Count - 1; i >= 0; --i) 
{
    if(GameManager.instance.blocks[i] == vectorToRemove) GameManager.instance.blocks.Remove(vectorToRemove);
}

您不应将 n 设置为数组大小,它必须是项目总大小的 n-1。

int n = GameManager.instance.blocks.Count-1;//last index is n-1
while (n >= 0)//0 is the first index 
{
    if (GameManager.instance.blocks[n] == new 
    Vector3(Mathf.RoundToInt(this.transform.position.x), 
      Mathf.RoundToInt(this.transform.position.y), 0))
      {
          GameManager.instance.blocks.Remove(new Vector3(Mathf.RoundToInt(this.transform.position.x), Mathf.RoundToInt(this.transform.position.y), 0));
      }
      n--;
 }