Why is it that when I run run this code to save an integer, the value that is being saved is being reset to 0?

private Save SaveData()
{
save.playerGold = playerGold;

            return save;
        }
        public void SaveGame()
        {
            save.playerGold = playerGold;

            Save lsave = SaveData();
            Debug.Log("SavedPG: " + save.playerGold);

            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
            bf.Serialize(file, lsave);
            file.Close();
        }

The function SaveGame() is linked to a button, but when I click on the button, the console says that the save.playerGold = 0; (The variable that is being serialized)

I have already checked that save.playerGold is greater than 0 with the code below:

public void FixedUpdate()
        {
            save.playerGold = playerGold;
            Debug.Log("spg: "+ save.playerGold + "pg" + playerGold);
        }

Are you sure that your two code snippets actually access the same instance of your Save class / struct? Are the two snippets inside the same class?

Your SaveData method seems to be completely redundant. Can you show how your “Save” class / struct looks like and tell us where the save variable is defined.

Never mind, thanks for the responses and I’ve managed to fix the problem.