- Home /
Question is off-topic or not relevant
Why the List in the class when using it is not the same in another class ?
I have this simple class :
using System;
using System.Collections.Generic;
[Serializable]
public class SaveGame
{
public List<SaveObject> saveObjects;
}
Now I'm using it another script in two places in one method at the bottom :
public void Save()
{
SaveGame saveGame = new SaveGame();
saveGame.saveObjects = new List<SaveObject>();
SaveObject saveObject = new SaveObject();
for (int i = 0; i < objectsToSave.Count; i++)
{
saveObject.gameObjectInstanceID = objectsToSave[i].gameObject.GetInstanceID();
var x = objectsToSave[i].GetComponents<Component>();
var stateQueryComponent = x.Where(component => component is IStateQuery).ToList();
List<KeyToValue> componentsState = new List<KeyToValue>();
foreach (var z in stateQueryComponent)
{
var w = z as IStateQuery;
componentsState.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
}
saveObject.position = objectsToSave[i].position;
saveObject.rotation = objectsToSave[i].rotation;
saveObject.scaling = objectsToSave[i].localScale;
saveObject.componentsState = componentsState;
saveGame.saveObjects.Add(saveObject);
string json = JsonUtility.ToJson(saveObject);
SaveSystem.Save(json);
}
}
I'm doing :
saveGame.saveObjects.Add(saveObject);
And using a breakpoint I see that saveObjects contains one item.
Then in the Load method in the same script I'm doing :
public void Load()
{
Dictionary<int, Transform> instanceIdToObject = objectsToSave
.ToDictionary(o => o.GetInstanceID(), o => o);
var saveString = SaveSystem.Load();
if (saveString != null)
{
SaveGame saveGame = JsonUtility.FromJson<SaveGame>(saveString);
foreach (var saveObject in saveGame.saveObjects)
Now when using a breakpoint on the foreach loop saveObjects list is empty. If I will make something complex and make the saveObjects List public static then the list will be with the item/s I added but making it public static is not the solution.
What else should I do to reference to the same saveObjects list with the added items ?
Answer by BSR16 · Oct 05, 2020 at 12:13 PM
You overlooked the following point: Lists keep a reference of the added item.
You have created a SaveObject instance just above the for loop in the Save function. In the first iteration, this instance was added to the list, but in subsequent iterations, it was not added as a new instance because the item corresponding to the same memory already exists in the list. Only values of this referenced object have been changed. At each iteration, you must create a new SaveObject object and add it to the list.
Dude, I've examined your code. You said, "I tried to move the SaveObject new instance inside the loop but it's still empty in the Load." because you have different problems than you asked.
First problem - "And using a breakpoint I see that saveObjects contains one item." : We solved it with the explanation above. So by creating a new SaveObject instance every time in the loop.
Second problem: You keep the list by solving the first problem but cannot save it to the file properly. It contains one record because you override the file but should append. Hence, fix the Save function in SaveSystem like this:
// File.WriteAllText(fileName, saveString); --> your line
// replace the top row with the following lines.
StreamWriter sw = File.AppendText(fileName);
sw.WriteLine(saveString);
sw.Close();
Third problem: You are saving objects of type SaveObject in the Save function in the SaveLoad script. But you are trying to reload it as SaveGame in the Load function in the same script. Fix that part like this:
// you do not save the SaveGame type, you save the SaveObject type!
// SaveGame saveGame = JsonUtility.FromJson<SaveGame>(saveString); --> wrong
// reload as below
string[] lines = saveString.Split('\n');
List<SaveObject> saveObjects = new List<SaveObject>();
foreach(string line in lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
saveObjects.Add(JsonUtility.FromJson<SaveObject>(line));
}
}
(Keep this in mind at this point, this part always adds to the file. You will probably want to write the file from scratch when the Save button is clicked. This part is on you.)
Fourth problem: You are setting back game objects using your InstanceIDs, but I noticed that the ids stored in the file and in the dictionary are not the same. This is caused by the following line in the Save function in the SaveLoad script: saveObject.gameObjectInstanceID = objectsToSave[i].gameObject.GetInstanceID();
Change it like this: saveObject.gameObjectInstanceID = objectsToSave[i].GetInstanceID();
I tried it and also saw it work that way. I hope it is clear in my explanations. The Github link you shared is not working. I think it is a work that can be useful to others if you share the GitHub link again when you fix it. Congratulations, go ahead!
BSR16 maybe you can look in my project I uploaded it to my one drive. It's only 16$$anonymous$$B size. Including the scripts and two cubes.
What I'm trying to do :
One single save file with al the gamobjects info.
To load the info back from the saved file.
To be able to save and load while the game is running and to load when running the game over again.
The problems :
The file now is saving only single gameobject info even if I have two gameobjects in the List in the SaveLoad script.
I tried to move the SaveObject new instance inside the loop but it's still empty in the Load.
How to use if everything will work with the StateTest script ? It's now on both cubes and I'm only saving now the cubes position rotation scaling but how to use with the StateTest to save also for example bool state ?
Here is a link for my project https://1drv.ms/u/s!AluY_2affYo7hFO4HZK5ITdXfbm-?e=csAnCt
$$anonymous$$y project on my one drive
Here is a link for github https://github.com/chocolade1972/Save-System
Follow this Question
Related Questions
Grab a specific item from a list 3 Answers
Adding more than one item to the list and saving it into JSON file problem 1 Answer
How do i convert this code snippet to a list? 1 Answer
Access list storing custom class variables from another script 1 Answer
Keep list of GameObjects between scenes 2 Answers