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.

  1. In the first scene to load create an Empty GameObject and name it “SceneHandler”.

  2. Create a new tag “SceneHandler” and add it to the “SceneHandler” GameObject

  3. Add the following “SceneHandler” script to the “SceneHandler” GameObject

  4. 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();
    }

}