'Loop through a list of Vector3's and see if it is another vector3 and remove it from the list
so I have a list of Vector3's and I would like to loop through it and see if it equals another Vector3.
I've tried to do this but it won't work i get an error that says
Index was out of range. Must be non-negative and less than the size of the collection.
Here is my code:
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--;
}
But i get the error previously stated, what would I change here?
Thanks
Solution 1:[1]
You shouldn't set n to your array size it must be n-1 of your total item size.
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--;
}
Solution 2:[2]
You shouldn't use "while" loops with Unity.
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barış Can Yılmaz |
| Solution 2 |
