- Home /
The question is answered, right answer was accepted
How to save the current scene the player is in using PlayerPrefs?
In my game players can move between different scenes, but if the game saves and loads it teleports the player to the right position, but the scene is the same.
I need a way to save current scene and load it.
Answer by pako · Dec 25, 2017 at 10:33 AM
In the first scene to load create an Empty GameObject and name it "SceneHandler".
Create a new tag "SceneHandler" and add it to the "SceneHandler" GameObject
Add the following "SceneHandler" script to the "SceneHandler" GameObject
See the CustomScript script below for example usage
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement;
public class SceneHandler : MonoBehaviour {
void Awake() { DontDestroyOnLoad(gameObject); } public void SaveScene() { int activeScene = SceneManager.GetActiveScene().buildIndex; PlayerPrefs.SetInt("ActiveScene", activeScene); } public void LoadScene() { int activeScene = PlayerPrefs.GetInt("ActiveScene"); //SceneManager.LoadScene(activeScene); //Note: In most cases, to avoid pauses or performance hiccups while loading, //you should use the asynchronous version of the LoadScene() command which is: LoadSceneAsync() //Loads the Scene asynchronously in the background StartCoroutine(LoadNewScene(activeScene)); } IEnumerator LoadNewScene(int sceneBuildIndex) { AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneBuildIndex); asyncOperation.allowSceneActivation = false; while (asyncOperation.progress < 0.9f) { yield return null; } asyncOperation.allowSceneActivation = true; } }
using UnityEngine;
//EXAMPLE USAGE OF Saving/Loading of Active Scene
public class CustomScript : MonoBehaviour { private SceneHandler sceneHandler;
void Awake () { sceneHandler = GameObject.FindGameObjectWithTag("SceneHandler").GetComponent<SceneHandler>(); } void CustomMethod() { sceneHandler.SaveScene(); sceneHandler.LoadScene(); } }
Hello, I know it may seem like a stupid question, but how could I apply this script in a game that each scene depends on buttons to be able to change scenes?