Foreach returning more information than intended
Hey guys, I've been trying to write some code that allows me to do the following:
Find All Players with Tag
Fill an Array with said Players
Find All Player Spells (in the prefab folder)
Make dictionary entries based on player name to fill in a list of spells
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.
Answer by Colthy · May 07, 2019 at 04:09 PM
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------
Your answer
Follow this Question
Related Questions
Using foreach to remove and delete bullet in List - C# 3 Answers
Getting "object reference not set" error when creating a list dictionary. 1 Answer
Compare GameObject with an array 1 Answer
Get object to check list for number of specific items 0 Answers
Problem with reading values from scripts on GameObjects in Lists 1 Answer