Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Getting error InvalidOperationException: Collection was modified, enumeration won't execute.

Discussion in 'Scripting' started by Doctor_Fork, Jul 3, 2020.

  1. Doctor_Fork

    Doctor_Fork

    Joined:
    Apr 12, 2020
    Posts:
    4
    I am making a shotgun for a game I am making, and I am using prefabs to shoot. I am new to unity, and just followed a tutorial from Youtube. In the video, it works fine, and we have the same code, so I don't know what is wrong. His video is from 2017, so something may have changed. Here's my C# code:
    Code (CSharp):
    1. void fire()
    2.     {
    3.         int i = 0;
    4.         foreach(Quaternion quat in pellets)
    5.         {
    6.             pellets[i] = Random.rotation;
    7.             GameObject p = Instantiate(pellet, BarrelExit.position, BarrelExit.rotation);
    8.             p.transform.rotation = Quaternion.RotateTowards(p.transform.rotation, pellets[i], spreadAngle);
    9.             p.GetComponent<Rigidbody>().AddForce(p.transform.forward * pelletFireVelocity);
    10.             i++;
    11.         }
    12.     }
    I have basically no idea how lists work, so please don't just explain it. It would be awesome if someone could provide code that would help.
     
  2. Hiktses

    Hiktses

    Joined:
    May 30, 2020
    Posts:
    19
    Are you getting this error when you fire the shotgun or before the game starts?
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    It's like it says on the tin: you changed the collection (list) when you were iterating it.

    One approach is to make an array of the list and iterate that, so that you can freely change the collection in the loop, something like:

    Code (csharp):
    1. var PelletArray = pellets.ToArray();
    2. foreach( Quaternion quat in PelletArray)
    3. // ... and the rest of your loop code here
    4.  
    Not to dig to far into it, but is there any reason you're even using a list of quaternions? In the above code you never use what is in the
    pellets[]
    list. You get each item out as
    quat
    and as far as I can see, you do nothing with it. Not only that, you immediately replace it with a new random rotation. Are you using that array somewhere else?

    Why not just do it with a count?

    Code (csharp):
    1. int numPellets = 7;
    2.  
    3. for (int i = 0; i < numPellets; i++)
    4. {
    5.   var quat = Rotation.random;
    6.  
    7.   // use quat here instead of pellets[i]
    8. }
     
    Hiktses likes this.