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");
    }

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.