Problem when changing a value in the list
Hi Guys,
I'm having a problem with my list and what happen is that when I change a single value on the list, all the values int the list changes.
Down Below is my code to setup my list.
void PreLoadBattleData()
{
//Preparing the needed List
List<int> tempList = new List<int>(2);
// 0 - 111 SquareNumber
for (int i = 0; i < 112; i++)
{
tempList.Add(0); //Add 0 for occupant
tempList.Add(mapData[i]); //Add terrain data
battleData.Add(tempList); //Then integrate it to BattleData
}
}
Then after running some functions I will arrive with this method.
void DeployUnit()
{
int unitSelected = battleManager.GetComponent<BattleManager>().popUpPage;
battleManager.GetComponent<BattleManager>().battleData[int.Parse(gameObject.transform.parent.name)][0] = (unitSelected + 1);
}
The last line should only change a single value in the list. In example battleData[50][0] the value from 0 will be changed to 1 but when I print them on the console.
All battleData[(from 0-111)][0] will print the value of 1 even though I only changed 1 part of it.
Please help, this seems basic but I could not find out where did I go wrong. I've tried debugging all the codes that will leave up to that method but only that method can change the values in my List.
Answer by GrafSpee · Oct 16, 2017 at 01:54 PM
Able to fixed it on my own. I use the same code when I change variables from a different script and figured that that script can't be incorrect. So I experimented with how I build the list. Below is what fixed the issue;
void PreLoadBattleData()
{
for(int i = 0; i < 112; i++)
{
List<int> tempList = new List<int>(2);
for (int x = 0; x < 2; x++)
{
tempList.Add(0);
}
battleData.Add(tempList);
}
for(int i = 0; i < 112; i++)
{
battleData[i][1] = mapData[i];
}
}
Although I am not sure how I am able to fix it because I don't see any difference aside from making the code more complicated. So I would appreciate it if someone can point it out for me.
Your answer
Follow this Question
Related Questions
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index 2 Answers
reorderable list of reorderable list items? (Editor) 0 Answers
Nested lists; How to add/decalre lists at runtime? 0 Answers
Adding to a List inside a Coroutine doesn't add properly? 1 Answer
Destroy GameObject in list then instantiate GameObject not working 1 Answer