- Home /
Problem not remove all prefab from list aftre the instantiate
Hi guys i've a list of prefabs in a list to instantiate, but i would like remove it after the instantiate from a list. I'don't know why with this script if the count is major of 6, instantiate only some prefabs and not all.
Any suggestion
best regards
private void spawnBlock() { Debug.Log(cards.Count.ToString()); float offset = 2f; int count = cards.Count; // Get remaing prefabs count
for(int i=0;i<count;i++)
{
Debug.Log(i);
GameObject go = cards[i]; // Get element from list
Instantiate(go, new Vector2(this.transform.position.x, transform.position.y - offset), Quaternion.identity);
cards.Remove(go); // Remove it from list (avoid duplication)
}
}
Answer by GoliathAT · Aug 17, 2021 at 06:51 AM
Try to inverse the loop. The problem right now is that you are changing the size of the array by deleting an item when iterating through it. So when you remove[i], then next remove[i] will have the same index as the last one.
for(int i = count; i > 0; i--)
{
}
This way you don't have to worry about removing an item, as it will not be targeted again in the next iteration.