- Home /
Store Current Level Using Preferances?
i m working on 2D game:
problem is here :
when player first level complete then going second level,player out (second level)then load first level not second level
Code:
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("triger fire");
if (other.gameObject.tag == "Player")
{
//Debug.Log("findgameobjecct:" + other.gameObject.tag);
gameovertext.SetActive(true);
PlayerManager.playerstop = true;
PlayerManager.obstaclestop = true;
StartCoroutine(gameover());
}
}
private IEnumerator gameover()
{
yield return new WaitForSeconds(3f);
//problem:in player second level and player out then load first level not second level
int num = PlayerPrefs.GetInt("Level",0);
SceneManager.LoadScene(num);
Debug.Log("InsideGameOver");
}
If you are getting an int in playerprefs, remove the 0 and the comma at line 21. If you wsnt to set an int, then change it to PlayerPrefs.SetInt....
Answer by Ak0rn · Jul 09, 2019 at 08:18 AM
Your issue is that your PlayerPref isn't updating the int of "Level" in each scene, your script is currently set to have "Level" as 0 so it will always load "0" in the build index.
Scene currentScene = SceneManager.GetActiveScene();
int num = PlayerPrefs.SetInt("Level", currentScene.buildIndex + 1);
SceneManager.LoadScene(num);
That should give you somewhere to start if it doesn't work straight away, can't currently test it.
If you want the correct level to reload when you die, simply put in a Scene$$anonymous$$anager.LoadScene(currentScene)
inside of "GameOver"
The above code will update the current level at the end of each level and then load it. Also very useful.
Your answer
![](https://koobas.hobune.stream/wayback/20220612204539im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Get score from list? 1 Answer
problem with playerprefs 1 Answer
PlayerPrefs setting to an existing int 0 Answers
what's the result of PlayerPrefs.Get... if the key/value was never set? 1 Answer
Set int to object from list? 0 Answers