Altering a Dictionary whilst altering its items

I have an event which several functions are subscribed to, two of which cause problems.

Function A removes target item from a Dictionary and then loops through all items and invokes IEnumerator which lerps them into their new position.
Function B is on the item itself. The item is faded out and then deleted.

However only after a single step of fade-out I get following message:
Collection was modified; enumeration operation may not execute.

It probably has something to do with that Function A removing the item from the Dictionary.

What are some direct workarounds for this? This is just a temporary script which is meant to do the job, its not a long-term solution. I could just pass the variable as parameter but that would add an ugly exception to rather clean codebase I have which could be a headache in the future.

Are you saying that your entire codebase doesn’t use parameters and adding one would tarnish that?

It’s kind of hard to understand what’s going on from your description without seeing some the code.

That error message typically means that you modified a collection while you were mid-way through enumerating it. For example, from inside a foreach loop.

Nothing in your description of your program sounds like it would necessarily involve doing that, although you do mention modifying a collection (removing an object from a dictionary), and if you did that badly you could conceivably generate this error.

If you want debugging help, you need to post your code.

1 Like