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*.gameObject.GetInstanceID();*

var x = objectsToSave*.GetComponents();*
var stateQueryComponent = x.Where(component => component is IStateQuery).ToList();
List componentsState = new List();
foreach (var z in stateQueryComponent)
{
var w = z as IStateQuery;
componentsState.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
}

saveObject.position = objectsToSave*.position;*
saveObject.rotation = objectsToSave*.rotation;*
saveObject.scaling = objectsToSave*.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(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 ?

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('

');
List saveObjects = new List();
foreach(string line in lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
saveObjects.Add(JsonUtility.FromJson(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_.gameObject.GetInstanceID(); Change it like this: saveObject.gameObjectInstanceID = objectsToSave*.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!