- Home /
Duplicate Question
How to implement a singleton
I have made a script with a counter in it, and then to make this counter keep count through the whole game, I am using DontDestroyOnLoad (transform.gameObject);. There is just the problem, that when i start on the first scene nothing is wrong but, then when I have played through a level and is back on the main scene, the counter(which is displayed) has been duplicated. I saw something about implementing a singleton in another thread, but I didnt really understand how I would implement it into my script. Do I have to make a seperate script with the singleton in, and then connect it to the script with the counter or what would the best way of doing it be?
Script:
static var energyObj : int = 5;
var counter : float;
function Awake () {
DontDestroyOnLoad (transform.gameObject);
}
function Start()
{
counter = 1800;
}
function Update () {
if (energyObj < 5) {
counter -= Time.deltaTime;
if(counter <= 0){
energyObj += 1;
counter = 1800;
Debug.Log("Energy is " + energyObj);
}
}
energyObj = Mathf.Clamp(energyObj, 0, 5);
if (energyObj > 5) {
energyObj = 5;
}
if (energyObj < 0) {
energyObj = 0;
}
}
function OnGUI () {
if (energyObj < 5) {
var minutes = Mathf.Floor(counter / 60).ToString("00");
var seconds = (counter % 60).ToString("00");
GUI.Label(new Rect(100,40,400,40),"To Next: " + minutes + ":" + seconds);
}
}
There's only one realistic way to have singleton-like concepts objects in Unity:
http://answers.unity3d.com/questions/663351/design-advice-power-up-system-static-variables.html
it has been the subject of incredible discussion on here. Note the many linked questions etc
Grid.hopeItHelpsYou() ! :)
I would forget about singletons unless you're an advanced experienced programmer. Learn how to use trivial Static classes, which are very often the solution you want.
Glad I could help, I've converted my comment to an answer.
Answer by robertbu · Mar 25, 2014 at 07:04 PM