Remove all elements from the list without the Clean () method, how?

0

For example I wanted to remove the elements from the list like this:

public class List : MonoBehaviour {

List<string> inventário = new List<string>();

void Start () {



    for(int i = 0;i<=10;i++){
        inventário.Add("slot" + i);
    }

    Debug.Log(inventário[1]);

    for(int i=0;i<inventário.Count;i++){
        inventário.Remove(inventário[i]);
    }

But for some reason it leaves only 5 elements in the list array.

    
asked by anonymous 06.08.2018 / 04:49

1 answer

1

Change this:

for(int i=0;i<inventário.Count;i++){
    inventário.Remove(inventário[i]);
}

So:

while (inventário.Count != 0) {
    inventário.Remove(inventário[0]);
}

The reason is that in its first% w / o of%, it removes the element in position 0, but then the element that was in position 1 goes to 0. Then you go to position 1 and remove the element that was there , and with that what was in 2 goes to 1, and so on. As a result, with each iteration you deleted one element and also saved another element, eliminating only half of them (those with even indexes).

Already in this for , it insists on removing the first element until there is no more a first element.

    
06.08.2018 / 05:30