How do switch scene with singleton pattern unity3d C#
I have to two UI text . One timer script and one score script .The scenes won't switch when the countdown timer reaches zero. Will dont destroy on load work if I a call that function in the score script change the scene ? I have points set to 50 . The scene will only change if the score is below 50 and the timer reach zero. Here are my script.
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Game : MonoBehaviour {
private MyClockScript myClock; void Start () { myClock = GetComponent(); }
// Update is called once per frame
void Update () {
if (myClock.m_leftTime < 0 || GameManagerSingleton.score > 0)
{
SceneManager.LoadScene("ui");
}
}
}
public class GameManagerSingleton : MonoBehaviour { public static GameManagerSingleton instance = null;
public static int score;
private Text text;
void Awake()
{
text = GetComponent <Text> ();
score = 0;
if (instance != null && instance != this)
Destroy(gameObject); // Ensures that there aren't multiple Singletons
instance = this;
}
void Update()
{
text.text = "Score: " + score;
Debug.Log("Score: " + score);
}
}
Answer by YoungDeveloper · Jun 15, 2016 at 11:00 AM
Best solution that works best for me personally is never again load the scene with singletons. Create fake preload scene (0) with all the singletons where they inizialize. If you want to reload the game or return to lobby, then load scene (1). And dont forget to call DontDestroyOnLoad() on singleton gameobjects.
What do you mean by preload scene . Where at on the singleton script would I call the DonDestroyOnLoad function ?
By preload scene i basically mean a basic scene, like any other, which does not serve the game itself any purpose, except for initalizing singletons. Calling dont destroy on gameobject ensures that gameobject wont be destroyed when scenes change.
void Awake() {
DontDestroyOnLoad(gameObject);
}
Answer by mr-gelmir · Jun 15, 2016 at 10:53 AM
Could you make sure the scene called "ui" really exists and is added to the Build settings? Unity can only load scenes that are included there.