I get HashSet have been modified while it was iterated over

Hello, i get this error:

InvalidOperationException: HashSet have been modified while it was iterated over
System.Collections.Generic.HashSet1+Enumerator[execute+h+tuf].CheckState () System.Collections.Generic.HashSet1+Enumerator[execute+h+tuf].MoveNext ()
execute+maps.calctarget2 () on that line: foreach (h.tuf adj in atttargetcp) {

This is despite already working with a copy of atttarget.
And i am not sure what i do wrong.

        int rang= new int();
        HashSet<h.tuf> atttarget=new HashSet<h.tuf>();
        HashSet<h.tuf> atttargetcp;
        public void targetgrid(Color col, h.tuf pos, int range) {
            atttarget.Add (pos);
            rang = range;
            calctargets ();
            setcolors (col);
        }
        void calctargets() {
            while (rang > 0) {
                atttargetcp = atttarget;
                calctarget2 ();
                rang--;
            }
        }
        void calctarget2() {
            foreach (h.tuf adj in atttargetcp) {
                foreach (h.tuf adj2 in mapcoordinatelist[adj].aadjacing.Values) {
                    atttarget.Add (adj2);
                }
            }
        }
        void setcolors(Color col) {
            foreach (h.tuf posi in atttarget) {
                GameObject niu = h.Instantiatetarget( uipref, uilayer);
                niu.GetComponent<Image> ().color = col;
                niu.transform.localPosition = new Vector3( posi.a,posi.b,0);
                niu.transform.GetComponent<RectTransform> ().sizeDelta = fieldsize;
            }
        }

You’re not using a copy of atttarget, on line 12 you’re assigning atttargetcp to atttarget (no copy is made, that’s just two references to the same HashSet.

If you want to make a copy you’ll need to change line 12 to something like:

atttargetcp = new ashSet<h.tuf>(atttarget);

Ah thankyou

1 Like