-2

I have an issue in Unity2D where when I exit to main menu from a scene, that scene saves itself. So what would happen is that I would exit to the main menu, load the left scene again, and my data from that scene is saved. So for example, I would move my player, exit to main menu, go back to the scene/level, and my player's position would be updated to where I moved it. This is an issue because usually I complete a level, and I can't replay it. Does anyone know how to solve this?

The only thing I'm using to reload my scene:

SceneManager.LoadScene(SceneManager.GetActiveScene().name);

1 Answers1

0

If you only have to save player's position, you can use static variable like below.

public static Vector3 playerPositionSaved = <your player posiiton>;

Save player's position data at OnDestroy() on your scene management class or do it manually.

But this code only saves while application is running and dissapear when application ends.

To save player's data even application ends, you should save data as file with format(Like JSON, XML and so on) or use Unity's PlayerPrefs class.

JSON format example, you can declare class for your save data like this. I usually use LitJson to generate json string and parse object from json string. But this time, i'll show you JsonUtility from unity api.

public class SaveData
{
    public static Vector3 playerPosition = Vector3.zero;
    public static Vector3 playerNickName = Vector3
}

and save & load data like this

// Save
public void SaveData(SaveData saveData)
{
    string savePath = Path.Combine(Application.persistantDatapath, "data.txt");
    string jsonData = JsonUtility.ToJson(saveData);
    File.WriteAllText(savePath, 
}

// Load
public void LoadData()
{
    string loadPath = Path.Combine(Application.persistantDatapath, "data.txt");
    string jsonData = File.ReadAllText(loadPath);
    SaveData loadedData = JsonUtility.FromJson<SaveData>(jsonData);

    // this is saved player's position data
    Vector3 playerSavedPosition = loadedData.playerPosition;
}

If you want to save all scene data, you should design well all of your class structures and save to file. Or you may bye some related assets. There are several assets to save and load scene data automatically.

  • You were on the right track with the static stuff. I knew statics saved between all scripts but I didn't know it went as far as scene transitions. I reviewed all my code and modified it and now it works fine, so thank you. – yassin eltaramsi Apr 29 '22 at 05:27