Home > Back-end >  issue with updating player level by loading scene
issue with updating player level by loading scene

Time:01-08

I'm having trouble saving and loading a scene. I have this code:

public void LoadData(Data data)
{
    this.sceneName = data.sceneName;
    SceneManager.LoadScene(sceneName);
    this.level = data.level;
}

public void SaveData(ref Data data)
{
    data.sceneName = SceneManager.GetActiveScene().name;
    data.level = this.level;
}

and when I have a line in my code that contains "SceneManager.LoadScene(sceneName);" is the player's level, which he writes at the beginning of the code as follows `public int level = 1; public int health = 100; I'm signing up incorrectly. The Player level object changes, but when I want to get it using player.level; it shows me level "1" even though it is equal to 2

All I know is that the problem occurs by loading the scene. When I remove the line SceneManager.LoadScene(sceneName); level updates normally

CodePudding user response:

When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately. So your level variable gets overwritten when the scene loads and resets back to 1.

One solution could be to store the new level value in a temporary variable before loading the scene, and then assign it to the level variable after the scene has finished loading. You can do this using the SceneManager.LoadSceneAsync function, which allows you to load the scene asynchronously and use a callback function to execute code after the scene has finished loading.

public void LoadData(Data data)
{
this.sceneName = data.sceneName;
int newLevel = data.level;

// Load the scene asynchronously and use a callback function to execute code after the scene has finished loading
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
asyncLoad.completed  = (operation) =>
{
    this.level = newLevel;
};
}

public void SaveData(ref Data data)
{
data.sceneName = SceneManager.GetActiveScene().name;
data.level = this.level;
}

This way, the level variable will not be overwritten when you load the scene, and it will retain its updated value.

Check out the SceneManager.LoadScene documentation for further details.

Alternatively you can set your level variable as static and it will keep its value between scenes.

CodePudding user response:

Thanks for the answer, but it didn't help. When I put Debug.Log in asyncLoad it shows me the correct level, while in other script I type player.level it shows me the default value, the same is also when I put Debug.Log outside asyncLoad.

  • Related