hi, i have a question.that is–
suppose i have 5 level and 2 scene start menu and win menu…in win menue has a next button…now when a level passed the win scene loading rightly…but now when i click next button it take me the next scene +1…but i need load next level of level 1 to 2…if win click next to 3…
have any methode? which can give me the previous scene index number or anyyy???
so now how can i do this?
Thanks.
When a scene unloads, everything in that scene is destroyed. If you need to remember something from the scene, you’ll need something that is persistent or doesn’t unload.
There are a few options, but one way to handle this is with a game object that is marked as DontDestroyOnLoad. This object will not be destroyed when the scene unloads and can be used to remember game state.
For example, you could have a persistent object to handle changing scenes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneHandler : MonoBehaviour
{
public static SceneHandler instance;
//The initial value here depends on your scene build indexes.
private int nextLevelSceneId = 0;
//This makes sure there is only ever one instance of SceneHandler
private void Awake()
{
if(instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject); //don't unload this when the scene changes
}
else
{
Destroy(gameObject);
}
}
public void LoadNextLevel()
{
SceneManager.LoadScene(nextLevelSceneId);
nextLevelSceneId++;
}
public void LoadWinScreen()
{
SceneManager.LoadScene("WinScene"); //or whatever your win scene is named
}
}
One key thing to be careful of with DontDestroyOnLoad objects is that you can’t rely on references set in the inspector to access these objects. So in this case, you would call these functions from another script with:
SceneHandler.instance.LoadNextLevel();
So for your button use case it will be a bit clunky because the button can’t reference the SceneHandler directly. You’ll need some other script present in the scene with a function that the button can call when pressed. You could add this to some other script you have in the “win” scene and have the button call this function.
public void RequestNextLevel()
{
SceneHandler.instance.LoadNextLevel();
}