Start is not called after reloading the level
Hi, I am making a class which it is supposed to load every time I load a level, but the methods Start and Awake is only loaded the first time this level is loaded, and as a result, the number of lives is not displayed when the level is restarted. Here is the important part of my class:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
//TODO: Cuando se recarga el nivel no fucniona bien! No vuelve a pasar por Star ni por Awake!
public class LevelManager : MonoBehaviour {
public Text timeText;
public Text scoreText;
public Text lifeText;
public Slider slider;
public static LevelManager levelManager; //Singleton
public int score = 0;
private Animator animator;
public float seconds = 0;
float minutes = 0;
int stars = 0;
void Awake(){
if (levelManager == null) { //Singleton
levelManager = this;
} else if (levelManager != this) {
Destroy (gameObject);
}
}
void Start(){
Debug.Log ("Start");
GameControl.Load ();
animator = GetComponent<Animator> ();
lifeText.text = "x" + GameControl.lives;
}
}
To load my level I simply do:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class LoadSceneOnClick : MonoBehaviour {
public void LoadByIndex(int sceneIndex)
{
SceneManager.LoadScene (sceneIndex);
}
}
Anyone know how to fix this? Is this maybe a bug? Thanks!
Answer by 5c4r3cr0w · Jan 11, 2017 at 01:04 PM
It's because you are creating a Singletone it will prevent Start() from getting called because GameObject calling Start() will get destroyed in Awake() and prevent duplication since gameobject form previous scene is not destroyed.
You should use OnLevelWasLoaded() instead of Start() as you need to call it when you load a new scene.
OnLevelWasLoaded() has been deprecated. You shouldn't use it when writing new code.
I removed the Singleton pattern, made a few changes and now it seems to work. Thank you both!
Answer by LK84 · Jan 11, 2017 at 01:25 PM
First of all Singletons (like Game Managers) should be applied to empty GameObjects. Plus, for a robust implementation of the singleton pattern in Unity have a look here: http://wiki.unity3d.com/index.php/Singleton All the other stuff not related to the Singletion (like the code in the Start() method) should be put in a seperated script on a seperated Game Object (which contains the relevant components) within the scene
Answer by AdmiralThrawn · Dec 20, 2017 at 08:24 PM
void Start() { ... }
works perfectly fine for Singleton Monobehaviours.
For more professional infos continue to read here: singleton-monobehaviour-script
Cheers!