Reputation: 3563
In my game on Unity3d I have many scenes a now I work on the save/load game. I can save the game, but if I want to load it, I need to load scene, which I need, then load all other parameters.
Or should I load all parameters first, save it with DontDestroyOnLoad()
and then load scene, which I need?
public void ButtonSave()
{
PlayerPrefs.SetFloat("transform position x" + currentActiveSlot, playerTransform.position.x);
PlayerPrefs.SetInt("task 1 completed" + currentActiveSlot, isTask1Completed);
PlayerPrefs.SetInt("latestSaveSlot", latestSaveSlot);
PlayerPrefs.SetInt("act number" + currentActiveSlot, 0);
PlayerPrefs.SetInt("step number" + currentActiveSlot, 0);
PlayerPrefs.SetString("sceneName" + currentActiveSlot, SceneManager.GetActiveScene().name);
PlayerPrefs.Save();
}
public void ButtonLoad()
{
playerTransform.position = new Vector3(PlayerPrefs.GetFloat("transform position x" + currentActiveSlot),
PlayerPrefs.GetFloat("transform position y" + currentActiveSlot),
PlayerPrefs.GetFloat("transform position z" + currentActiveSlot));
isTask1Completed = PlayerPrefs.GetInt("task 1 completed" + currentActiveSlot);
//gameManager.currentActNumber = PlayerPrefs.GetInt("act number" + currentActiveSlot);
//act_2.stepNumber = PlayerPrefs.GetInt("step number" + currentActiveSlot);
//SceneManager.LoadScene(PlayerPrefs.GetString("sceneName" + currentActiveSlot));
}
Upvotes: 1
Views: 743
Reputation: 125275
You are supposed to load the scene first with SceneManager.LoadScene
then load the Player settings with your PlayerPrefs
code.
public void ButtonLoad()
{
SceneManager.LoadScene(PlayerPrefs.GetString("sceneName" + currentActiveSlot));
playerTransform.position = new Vector3(PlayerPrefs.GetFloat("transform position x" + currentActiveSlot),
PlayerPrefs.GetFloat("transform position y" + currentActiveSlot),
PlayerPrefs.GetFloat("transform position z" + currentActiveSlot));
isTask1Completed = PlayerPrefs.GetInt("task 1 completed" + currentActiveSlot);
}
Not a good idea to save the variables invidually. You can see the proper way of saving and loading scenes here.
EDIT:
But in my case after loading scene, would other part of the method execute?
Yes/No.
After SceneManager.LoadScene
is called, the rest of the code in that function will execute but the execution will be done in the-same scene not in the newly loaded scene. Because of this, you will lose the player settings you just loaded.
So, I don't think that will be useful to you. Put the Player Settings code in the Awake
or Start
function to automatically load the Player Settings after loading the scene.
public void ButtonLoad()
{
SceneManager.LoadScene(PlayerPrefs.GetString("sceneName" + currentActiveSlot));
}
void Awake()
{
isTask1Completed = PlayerPrefs.GetInt("task 1 completed" + currentActiveSlot);
//...other PlayerPrefs.GetInt code
}
Upvotes: 2