Values are saved in every object in Array of objects
I have a problem with array of objects. After every loop in for loop every object(name, x, y) are saved in all of them.
To make things clearer: i loop through my Objects giving every one a set of specific values to be saved later in JSON. Soo on the first loop i have name = one, x =1, y=1 and its for the container[0] only. Then after second loop when i set name = two, x=2, y =2 for container[1] then the container[0] and every other that have any values set will have the same values as container[1]. Soo after few loops i don't have every value for every object saved but instead i have X ammount of duplicated values from the last loop.
Here's my code: https://pastebin.com/E7RBPrps
Thanks in advance for your help.
Answer by Alanisaac · Jan 13, 2019 at 06:26 PM
The problem is that you only ever have one instance of PlayerData
. Every index in your array 1...N is storing a reference back to that same, single object. Instead, if you want each index in the array to store its own instance, you need to construct a new instance for each index in the array. From a code perspective, what that means is you should move these lines:
PlayerData tempData = new PlayerData();
tempData.name = "a";
tempData.x = 0;
tempData.y = 0;
So that they go within the first for loop to initialize the data, like so:
for (int i = 0; i < FloorContainer.transform.childCount; i++)
{
PlayerData tempData = new PlayerData();
tempData.name = "a";
tempData.x = 0;
tempData.y = 0;
playerData[i] = tempData;
}
Thanks, that was exactly the answer i needed. I also modified it a little to get rid of the tempData and now it looks like this:
for (int i = 0; i < FloorContainer.transform.childCount; i++)
{
playerData[i] = new PlayerData();
playerData[i].name = FloorContainer.transform.GetChild(i).name;
playerData[i].x = FloorContainer.transform.GetChild(i).GetComponent
().x;
playerData[i].y = FloorContainer.transform.GetChild(i).GetComponent
().y;
}
And right now i try to understand how to save this objects array into JSON with simple JSON... But thanks man. You've been very helpfull!
Your answer
Follow this Question
Related Questions
Json to array of objects C# 1 Answer
Assaigning objects in class 2 Answers
How to get an object (that is a prefab) from an array and instantiate it (C#) 1 Answer
Creating and destroying SELECTED objects and... sorting arrays?? 0 Answers
Having problems with custom objects in my array - BCE0019 0 Answers