2
\$\begingroup\$

In Unity, I'm trying to save the game data to a file to be loaded upon the game reopening. But for some reason it is not saving and I cannot figure out why.

I have it so that if it cannot find that save file, it gives the player 3 items to start with and then tries to save that to the PersistingData. But then I close and reopen the game and it does not stay, and gets defaulted to 0.

Anyone know what I did wrong?

The PersistentData code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class PersistentData : MonoBehaviour {

    public static PersistentData dataObject;

    //Persistent Data here
    public int amps = 0;
    //Capacitors
    public int cap1v;
    public int cap3v;
    public int cap5v;
    public int cap9v;
    public int cap12v;
    public int cap24v;
    //Statistics
    public int totalDistance;
    public int lifetimeAmps;
    public int totalCapsUsed;
    public float lifetimeTimeInSeconds;
    public int numberOfRuns;
    public int distanceRecordNoCaps;
    public int distanceRecordWithCaps;
    public float highestAvgVoltage;
    public float longestRunInSeconds;
    public float highestAmpsEarned;

    //check if this object already exists and make sure its not destroyed every level
    private void Awake() {
        if (dataObject == null) {
            DontDestroyOnLoad(gameObject);
            dataObject = this;
        }
        else if (dataObject != this) {
            Destroy(gameObject);
        }
    }

    public void Save() {
        //setup for saving
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");

        //Add the data here too
        PlayerData data = new PlayerData();
        data.amps = amps;

        data.cap1v = cap1v;
        data.cap3v = cap3v;
        data.cap5v = cap5v;
        data.cap9v = cap9v;
        data.cap12v = cap12v;
        data.cap24v = cap24v;
        //Statistics
        data.totalDistance = totalDistance;
        data.lifetimeAmps = lifetimeAmps;
        data.totalCapsUsed = totalCapsUsed;
        data.lifetimeTimeInSeconds = lifetimeTimeInSeconds;
        data.numberOfRuns = numberOfRuns;
        data.distanceRecordNoCaps = distanceRecordNoCaps;
        data.distanceRecordWithCaps = distanceRecordWithCaps;
        data.highestAvgVoltage = highestAvgVoltage;
        data.longestRunInSeconds = longestRunInSeconds;
        data.highestAmpsEarned = highestAmpsEarned;

        //actually writing the data
        bf.Serialize(file, data);
        file.Close();
    }

    public void Load() {
        if (File.Exists(Application.persistentDataPath + "/playerInfo.dat")) {
            print("Save File Found");
            //setup for loading
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            PlayerData data = (PlayerData)bf.Deserialize(file);

            //Data Here Too
            amps = data.amps;

            data.cap1v = cap1v;
            data.cap3v = cap3v;
            data.cap5v = cap5v;
            data.cap9v = cap9v;
            data.cap12v = cap12v;
            data.cap24v = cap24v;
            //Statistics
            data.totalDistance = totalDistance;
            data.lifetimeAmps = lifetimeAmps;
            data.totalCapsUsed = totalCapsUsed;
            data.lifetimeTimeInSeconds = lifetimeTimeInSeconds;
            data.numberOfRuns = numberOfRuns;
            data.distanceRecordNoCaps = distanceRecordNoCaps;
            data.distanceRecordWithCaps = distanceRecordWithCaps;
            data.highestAvgVoltage = highestAvgVoltage;
            data.longestRunInSeconds = longestRunInSeconds;
            data.highestAmpsEarned = highestAmpsEarned;

            file.Close();
        }
        else if(!File.Exists(Application.persistentDataPath + "/playerInfo.dat")) { //If no save file, default the settings
            print("No Save File Found");
            dataObject.cap1v = 3;
            Save();
        }
    }

    private void Update() {
        print(dataObject.cap1v);
    }
}

[Serializable]
class PlayerData {

    //Persistent Data goes here
    public int amps = 0;
    //Capacitors
    public int cap1v = 0;
    public int cap3v = 0;
    public int cap5v = 0;
    public int cap9v = 0;
    public int cap12v = 0;
    public int cap24v = 0;
    //Statistics
    public int totalDistance;
    public int lifetimeAmps;
    public int totalCapsUsed;
    public float lifetimeTimeInSeconds;
    public int numberOfRuns;
    public int distanceRecordNoCaps;
    public int distanceRecordWithCaps;
    public float highestAvgVoltage;
    public float longestRunInSeconds;
    public float highestAmpsEarned;
}

And the Script trying to access the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MainMenuUI : MonoBehaviour {

    public Text capText;
    public Text ampText;

    private int capCount;
    private int ampCount;

    // Use this for initialization
    void Start () {
        PersistentData.dataObject.Load(); //Load data

        ampCount = PersistentData.dataObject.amps; //Load Correct Amp Count
        LoadCapCount(); //Load the total Cap count

        ampText.text = ((int)ampCount).ToString(); //Set amp count on UI
        capText.text = ((int)capCount).ToString(); //Set amp count on UI
    }

    void LoadCapCount() {
        capCount =
        PersistentData.dataObject.cap1v +
        PersistentData.dataObject.cap3v +
        PersistentData.dataObject.cap5v +
        PersistentData.dataObject.cap9v +
        PersistentData.dataObject.cap12v +
        PersistentData.dataObject.cap24v;
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ This really needs to be cut down to an MVP. Minimal Verifiable Problem. \$\endgroup\$ – Almo Jun 23 '18 at 1:27
4
\$\begingroup\$

Let's work though this logically:

dataObject.cap1v prints zero. But in the path where no save file was found, we set it to 3. So (barring outside interference) we must not have taken that path.

Which means we did find a save file. So why didn't we load its saved value into dataObject.cap1v?

Because we loaded it into a new object called data, data.cap1v. Then did nothing with this temporary object reference, so it vanishes from the scope at the end of the Load method, leaving all our data still at its default values.

\$\endgroup\$
  • \$\begingroup\$ My load method was screwed up. Its fixed now \$\endgroup\$ – dka13 Jun 23 '18 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.