In Unity, I manage to go back to the last scene by clicking the Device Android back button but the problem is when I am in the 3rd scene and I want to go back to 2nd and then back to 1st scene.
From 3rd to 2nd scene, when I click back button it goes successfully but when I press the back button again from 2nd scene to 1st scene it doesn't go. It looks like that the back button works only for the first time.
Here is my c# code:
public class SceneLoader : MonoBehaviour
{
private float seconds = 0.5f;
private static int lastScene;
private int currentScene;
private void Awake()
{
currentScene = SceneManager.GetActiveScene().buildIndex;
}
private void Update()
{
BackButtonPressed();
}
public void LoadNextScene(int numberOfSceneToLoad)
{
StartCoroutine(LoadScene(numberOfSceneToLoad));
}
private IEnumerator LoadScene(int numberOfScene)
{
currentScene = SceneManager.GetActiveScene().buildIndex;
SetLastScene(currentScene);
yield return new WaitForSeconds(seconds);
SceneManager.LoadScene(numberOfScene);
}
private void BackButtonPressed()
{
if (Input.GetKey(KeyCode.Escape))
{
Debug.Log("Current scene: " + currentScene);
Debug.Log("Last Scene (scene to load): " + GetLastScene());
SceneManager.LoadScene(GetLastScene());
currentScene = GetLastScene();
Debug.Log("Now the Current scene is: " + currentScene);
}
}
public static void SetLastScene(int currentSceneToLastScene)
{
lastScene = currentSceneToLastScene;
}
public static int GetLastScene()
{
return lastScene;
}
public void QuitGame()
{
Application.Quit();
}
}
Thanks in advance.