attackers list. For vs foreach?

So what happens is the method restart time is called anytime a n enemy hits its opponent
the error im getting is InvalidOperationException: Collection was modified; enumeration operation may not execute.

here is the script basically im asking for someone to show me how i can configure this script to correctly
remove the player from the attackerslist if the conditions are met

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class Stats : NetworkBehaviour
{
    public bool hasbeenattacked;
    List<GameObject> party = new List<GameObject>();
    public List<GameObject> attackerslist = new List<GameObject>();
    public Transform head;
    [SyncVar]
    public int level;
    [SyncVar]
    public string username;
    [SyncVar]
    public float myhp;
    [SyncVar(hook = "hphook")]
    public float hp;
    public bool dualwield;
    public GameObject weapontwo;
    [SyncVar]
    public float currenthp;
    public float attacklisttimer;
    public float staminacost;
    [SyncVar]
    public float maxhp;
    public float stamina;
    public float currentstamina;
    public float maxstamina;
    public float speed;
    public float currentspeed;
    public float maxspeed;
    public float strength;
    public float currentstrength;
    [SyncVar]
    public string charactername;
    public float maxstrength;
    public GameObject hpbar;
    [SyncVar]
    public float damage;
    public GameObject shield;
    public GameObject weapon;
    public Animator anim;
    public Slider externalhpbar;
    public Slider staminabar;
    public Slider externalstaminabar;
    public bool checkhp;
    public Text nametext;
    public GameObject player;
    public InputField setcharactername;
    public GameObject okbutton;
    public GameObject nameinput;
    public GameObject externalguistamina;
    public bool growstamina;
    public bool timerstart;
    public float timetillfullstamina;
    public GameObject arrow;
    public float staminagain;
    public float staminagaintime;
    public float circlevalue;
    public Image circlehp;
    public AudioClip shieldblock;
    public AudioClip gethit;
    public AudioClip death;
    public AudioClip selectobject;
    public AudioSource playeraudio;
    public GameObject targeting;
    public GameObject nameblock;
    public GameObject weaponone;
    public GameObject UIuseobject;
    public bool noshield;
    [SyncVar]
    public int xp;
    [SyncVar]
    public int xpgain;


    void circlehpchange()
    {
        circlevalue = 1 - currenthp;
        circlehp.CrossFadeAlpha(circlevalue, 0.5f, true);
    }

    public void takingdamage(float damage)
    {

        {
            if (!isServer)
            {
                return;
            }
            anim.SetTrigger("gethit");
            playeraudio.clip = gethit;
            playeraudio.Play();
            Rpc_hit();
            myhp -= damage;
            currenthp = hp / maxhp ;
            externalhpbar.value = Mathf.Lerp(externalhpbar.value, currenthp, 1f);



            if (hp <= 0 && this.transform == this.transform.root)
            {
                playeraudio.clip = GetComponent<Stats>().death;
                playeraudio.Play();
                if (isServer && transform.tag != "player")
                {
                    foreach (GameObject player in attackerslist)
                    {
                        player.GetComponent<Stats>().xp += xpgain;
                        }
                   
                }
                Rpc_died();
                Destroy(this.gameObject);
            }

        }
    }




    [ClientRpc]
    void Rpc_hit()
    {
        anim.SetTrigger("gethit");
        playeraudio.clip = gethit;
        playeraudio.Play();
    }






        public void setmyname()
    {

        charactername = setcharactername.text;
        nametext.text = charactername;
        Cmd_setname(charactername);
        okbutton.SetActive(false);
        nameinput.SetActive(false);

    }


    [Command]
    public void Cmd_setname(string charactername)
    {

        nametext.text = charactername;
        Rpc_setname(charactername);

    }




  [ClientRpc]
    public void Rpc_setname(string charactername)
    {

        nametext.text = charactername;

    }
    void hphook(float hp)
    {
       
        currenthp = hp / maxhp;
        externalhpbar.value = Mathf.Lerp(externalhpbar.value, currenthp, 15f);
    }


    void staminafilling()
    {
        if (growstamina == true)
        {
            StartCoroutine(staminafiller());
            if (stamina >= maxstamina)
            {
                growstamina = false;
                timerstart = false;

            }
        }

    }



    void staminanotfull()
    {
        if (stamina != maxstamina && timerstart == false)
        {

                StartCoroutine(staminafill());

        }
    }


    IEnumerator staminafiller()
    {
        if (growstamina == true && stamina < maxstamina)
        {
            stamina += staminagain;
            yield return new WaitForSeconds(staminagaintime);
            StartCoroutine(staminafiller());
            if (stamina >= maxstamina)
            {
                growstamina = false;
                timerstart = false;
            }
            StopCoroutine(staminafiller());

           
        }


    }


    IEnumerator staminafill()
    {
        timerstart = true;
        yield return new WaitForSeconds(timetillfullstamina);
        growstamina = true;


    }



    [ClientRpc]
    void Rpc_died()
    {
        playeraudio.clip = GetComponent<Stats>().death;
        playeraudio.Play();
        Destroy(this.gameObject);
    }
    void strengthdamage()
    {

    }


    void staminacalculate()
    {
        currentstamina = stamina / maxstamina;


        staminabar.value = Mathf.Lerp(staminabar.value, currentstamina, 15f);
        externalstaminabar.value = Mathf.Lerp(externalstaminabar.value, currentstamina, 15f);

    }



    [Command]
    void Cmd_addtoparty(GameObject player)
    {
        party.Add(player);
    }


    public void addtoattackers(GameObject player)
    {
        attackerslist.Add(player);
        hasbeenattacked = true;
        if(isLocalPlayer)
        {
            Cmd_addtoattackers(player);
            Cmd_attacked(hasbeenattacked);
        }
        if(isServer)
        {
            Rpc_addtoattackers(player);
            Rpc_attacked(hasbeenattacked);
        }
       if(hasbeenattacked == true)
        {
            StartCoroutine(attacklisttime());
            hasbeenattacked = false;
            if (isLocalPlayer)
            {
                Cmd_attacked(hasbeenattacked);
            }
            if (isServer)
            {
                Rpc_attacked(hasbeenattacked);
            }


        }
    }



    public IEnumerator attacklisttime()
    {
        yield return new WaitForSeconds(attacklisttimer * Time.deltaTime);
        if(isLocalPlayer)
        {
            if (attackerslist.Count != 0)
                lock (attackerslist)
                    foreach (GameObject player in attackerslist)
            {
                    if (attackerslist.Count != 0)
                    {

                        attackerslist.Remove(player);
                        if (isLocalPlayer)
                        {
                            Cmd_removefromattackers(player);
                        }
                        if (isServer)
                        {
                            Rpc_removefromattackers(player);
                        }
                    }
               
            }
        }
        if(isServer && transform.tag == "enemy")
        {
            if (attackerslist.Count != 0)
            {
                if (GetComponent<AItargeting>().playertarget != null)
                {
                    if (GetComponent<AItargeting>().npctargetdistance > 10)
                    {
                        lock (attackerslist)
                            foreach (GameObject player in attackerslist)
                        {
                            if (attackerslist.Count != 0)
                            {
                                attackerslist.Remove(player);
                                if (isLocalPlayer)
                                {
                                    Cmd_removefromattackers(player);
                                }
                                if (isServer)
                                {
                                    Rpc_removefromattackers(player);
                                }
                            }
                        }
                    }
                }
            }
           
        }
    }


    [Command]
    void Cmd_removefromattackers(GameObject player)
    {
        attackerslist.Remove(player);
        Rpc_removefromattackers(player);
    }

    [ClientRpc]
    void Rpc_removefromattackers(GameObject player)
    {
        {
            attackerslist.Remove(player);
        }
    }


    public void restarttime()
    {
        StopCoroutine(attacklisttime());
        StartCoroutine(attacklisttime());
        if(isLocalPlayer)
        {
            Cmd_restarttime();
        }
        if(isServer)
        {
            Rpc_restarttime();
        }
    }


    [Command]
    void Cmd_restarttime()
    {
        StopCoroutine(attacklisttime());
        StartCoroutine(attacklisttime());
        Rpc_restarttime();
    }


    [ClientRpc]
    void Rpc_restarttime()
    {
        StopCoroutine(attacklisttime());
        StartCoroutine(attacklisttime());

    }


    [ClientRpc]
    void Rpc_attacked(bool attacked)
    {
        hasbeenattacked = attacked;
    }

    [Command]
    void Cmd_attacked (bool attacked)
    {
        hasbeenattacked = attacked;
        Rpc_attacked(attacked);
    }


    [ClientRpc]
    void Rpc_addtoattackers(GameObject player)
    {

            attackerslist.Add(player);
       
    }

    [Command]
    void Cmd_addtoattackers(GameObject player)
    {
        attackerslist.Add(player);
        Rpc_addtoattackers(player);
    }

    // Use this for initialization
    void Start()
    {

        anim =GetComponent<Animator>();
        if (GetComponent<Charactersize>() != null)
        {
            if (GetComponent<Charactersize>().weight > 200 && transform.tag != "player")
            {
                GetComponent<AItargeting>().playertoofar *= 4;
            }
        }
        if (transform.tag == "player")
        {
            party.Add(gameObject);
            if (isLocalPlayer)
            {
                Cmd_addtoparty(gameObject);
            }
            circlehp.canvasRenderer.SetAlpha(0.0f);
        }
        if (isLocalPlayer)
        {
            hpbar.SetActive(false);
            externalguistamina.SetActive(false);
            nameblock.SetActive(false);
        }

        if (!isLocalPlayer)
        {
            if (transform.tag == "player")
            {
                okbutton.SetActive(false);
                nameinput.SetActive(false);
            }

        }
    }




    // Update is called once per frame
    void Update()
    {
        hp = myhp;
        if (transform.tag == "player" && isLocalPlayer)
        {
            staminacalculate();
            staminanotfull();
            staminafilling();
            circlehpchange();
        }

    }

}

One way is to be explicit and make a list of “ToBeRemoved” things as you process the list, but do not change the original list as you iterate through. Finally at the end you modify the original list by removing the ones in your ToBeRemoved list.

Another way to do it is to snapshot the List<> when the for or foreach loop starts by using the .ToArray() method on it to get an actual array out of it. Then you iterate all items in the array, and at that time you can directly remove things from the List<> because you’re not using it anymore.

Couple of things here. Please consider posting just the relevant code in the future lol.
Took some time to skim through all of that to find what you were probably actually talking about. sigh.

Okay, so if I was looking at the right spot, it looks like you just want to remove the player from 1 list or another.
Then, you want to remove every player from the list (essentially clear it).
So, while @Kurt-Dekker 's advice is cool, in this very particular case, I believe you could loop through the list, remove from the one list or the other… don’t do anything with the player (during the loop).
After the loop, just do: attackerslist.Clear();
:slight_smile: