- Home /
Load previous scene
Hello, after completing different tutorials, I ventured out on my own to try to see what I could create, but I am stuck. I have a player and when it collides with a star the player leaves scene1 and is sent to a bonus scene with a timer. Bonus scene works fine with timer running, but when the time runs out how do I get back to previous scene1 where the player left off? Eventually I will have random levels loading and whenever bonus object is triggered, switch to bonus scene, the time runs out and player returns to previous level. Looking for some code examples. I think it has something to do with Var, PlayerPrefs and maybe DontDestroyOnLoad, but I am confused what to write and where to put this code. This is my script for bonus scene and timer.
script attached to star object.
public class BonusStar : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
SceneManager.LoadScene("BonusScene");
}
}
script timer on Bonus scene.
public class Timer : MonoBehaviour {
public Text timer;
public float countDown = 15;
void Start()
{
timer = GetComponent<Text>();
}
void Update()
{
countDown -= Time.deltaTime;
timer.text = countDown.ToString("f0");
if (countDown <= 0)
{
//back to previous scene1?
}
}
}
Answer by kornstar83 · Jun 08, 2017 at 05:08 PM
reloading the last scene is relatively easy, just store the name of the active scene into a string and when the bonus scene calls the SceneManager.LoadScene (string) just pass in the saved string name,
but while going in between scenes the values can be lost so you will either need to have them on a script that is set to DontDestroyOnLoad or simply save the string into the PlayerPrefs.
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player") {
PlayerPrefs.SetString ("lastLoadedScene", SceneManager.GetActiveScene ().name);
SceneManager.LoadScene ("BonusScene");
}
}
Then on your Bonus Scene Script you would put,
public Text timer;
public float countDown = 15;
void Start()
{
timer = GetComponent<Text>();
}
void Update()
{
countDown -= Time.deltaTime;
timer.text = countDown.ToString("f0");
if (countDown <= 0)
{
string sceneName = PlayerPrefs.GetString("lastLoadedScene");
SceneManager.LoadScene(sceneName);//back to previous scene1?
}
}
That should solve your scene loading problem but having the player go back to where they where when the level scene is loaded again is a whole other bucket of worms.