Foreach returning more information than intended

Hey guys, I’ve been trying to write some code that allows me to do the following:

  1. Find All Players with Tag
  2. Fill an Array with said Players
  3. Find All Player Spells (in the prefab folder)
  4. Make dictionary entries based on player name to fill in a list of spells
  5. Make sure it works with multiple players

I’ve managed to get the first 4 points working without much of a hiccup, but when I introduced a second GameObject tagged as “Player” to the scene, both of the “Player” objects started receiving the spells from both Prefab folders, even though their names are different. I’ve been banging my head on this for hours and I’m sure it’s something silly, but I can’t figure it out.

Here’s the code:

//Find Players
        Players = GameObject.FindGameObjectsWithTag("Player");
        //make dictionary for each player and all of his spells
        playerSpellDict = new Dictionary<BasePlayer, List<BaseSpell>>();
        foreach(var player in Players)
        {
            //assign baseplayer to a var
            BasePlayer basePlayer = player.gameObject.GetComponent<BasePlayer>();
            //Get All Player Spells
            string playerName = player.GetComponent<BasePlayer>().playerName;
            Object[] playerPrefabList = Resources.LoadAll("Prefabs/" + playerName, typeof(GameObject));
            //For each object the player's Prefab folder, add them to list of spells
            foreach (GameObject obj in playerPrefabList)
            {
                //add all player spells to list MIGHT HAVE TO REWORK
                playerSpellList.Add(obj.gameObject.GetComponent<BaseSpell>());
            }
            //make dictionary entries for each player and all of his spells
            if (!playerSpellDict.ContainsKey(basePlayer))
            {
                playerSpellDict.Add(basePlayer, playerSpellList);
                basePlayer.hasSpells = playerSpellList;
                //foreach(var v in playerSpellDict)
                //{
                //    Debug.Log(v.Key.ToString() + " " + string.Join(",", v.Value));
                //}
            }
        }

Thanks in advance.

I found the issue - I wasn’t disposing of the information of the list from previous players, so it just kept on piling up. Fixed the issue by creating a new instance of the list every time there’s a new player in the foreach loop.

Here’s the code:

------code snippet------
foreach(var player in Players)
         {
             playerSpellList = new List<BaseSpell>(); //ADDED THIS
             //assign baseplayer to a var
             BasePlayer basePlayer = player.gameObject.GetComponent<BasePlayer>();
             //Get All Player Spells
------code snippet------