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
CodePudding user response:
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--;
}
CodePudding user response:
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);
}