Problem is not reproducible or outdated
how to use SceneManager.sceneLoaded replacing OnLevelWasLoaded
Hello: I found that the score points in my project is kept even if i restart the game or reload the current scene. the score points is kept in a static variable. here is the script:
public class ScoreManager : MonoBehaviour {
public static int score;
Text text;
void Awake()
{
text = GetComponent<Text>();
score = 0;
}
void Update () {
text.text = "Score: " + score;
}
now I want to clear that score points every time i restart my game. I tried to search a way to solve this.
at first, i found this method:
void OnLevelWasLoaded(int level)
{
if (level==0)
{
ScoreManager.score = 0;
}
}
but it looks like the unity have abandoned this function after version 5.3 (i'm using unity 5.5). Then i found the SceneManager.sceneLoaded method, i added those lines to my script:
void OnEnable()
{
SceneManager.sceneLoaded += Loadedscene;
}
void OnDisable()
{
SceneManager.sceneLoaded -= Loadedscene;
}
void Loadedscene(Scene scene,LoadSceneMode mode)
{
if (scene.name=="Start")
{
ScoreManager.score = 0;
}
}
but it didn't work as i expected.
can anyone help me to solve this, please? thank you.
what happens when you print the name of the scene passed by that event?
So,
void Loadedscene(Scene scene,LoadScene$$anonymous$$ode mode)
{
Debug.Log (scene.name, scene.buildIndex);
}
doesn't print or do anything? Are you sure it's being subscribed? Does the below print anything if you put that before your subscription?
void OnEnable ()
{
Debug.Log ("I am trying to subscribe!");
}
Answer by herDev · Mar 07, 2017 at 08:16 AM
Here you go:
Scene scene = SceneManager.GetActiveScene();
if (scene.buildIndex == insertSceneBuildIndexHere) {
//Do something
}
or
if (scene.name == insertSceneNameHere) {
//Do something
}
thanks. i followed your advice, the script:
void OnEnable()
{
Scene$$anonymous$$anager.sceneLoaded += Loadedscene;
}
void OnDisable()
{
Scene$$anonymous$$anager.sceneLoaded -= Loadedscene;
}
void Loadedscene(Scene scene,LoadScene$$anonymous$$ode mode)
{
scene = Scene$$anonymous$$anager.GetActiveScene();
if (scene.buildIndex==0)
{
Score$$anonymous$$anager.score = 0;
}
}
but it didn't work. the score is still store into the static variable after my character died in game. maybe i didn't do it right.
I don't think you need
scene = Scene$$anonymous$$anager.GetActiveScene();
because you're passing the scene in already.