Y
Y
Yura Mailler2020-12-24 20:41:13
C++ / C#
Yura Mailler, 2020-12-24 20:41:13

Why is the unit complaining about the code?

I'm trying to iterate over a list, but for some reason unity throws an error:

5fe4d23f8e3e6386004256.png

Here is the place where the error occurs:

foreach (int item in sv.ItsNum) //жалуется здесь 
        {
            Debug.Log(item);
            if(Num == item)
            {
                StartCoroutine(Skin());
            }
            else
            {
                sv.ItsNum.Add(Num);
                
            }
                
        }

I think it's because of foreach but not a fact

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
freeExec, 2020-12-24
@Yura111

No, it's bad for him.
sv.ItsNum.Add(Num);
You can't change the collection you're iterating over. If you stupidly translated the error message, you wouldn't have to start a topic at all.
PS
Yes, here is the code itself with a bug, the longer the array, the more Nums will be added to it. And so it could be rewritten on two lines with Linq.

G
Griboks, 2020-12-24
@Griboks

I think this is due to the fact that "Collection was modified". In other words, you are iterating over and modifying the collection at the same time. And sharp does not want to understand your collection frauds, so it refuses to work and spits a mistake at you.
For those who are especially lazy, there is a secret method that will make sharp work in this mess. All you have to do is... slip him a copy of the collection:

foreach (int item in sv.ItsNum.ToList()) //тупо копируем
        {
            Debug.Log(item);
            if(Num == item)
            {
                StartCoroutine(Skin());
            }
            else
            {
                sv.ItsNum.Add(Num);
                
            }
                
        }

It should also be noted that stupidly (and even smartly) copying a collection is not very good in every sense.

V
Vasily Bannikov, 2020-12-26
@vabka

I think it's because of foreach but not a fact

You're right.
You cannot modify the sheet you are currently iterating over.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question