Countdown Timer
I am trying to make a script that counts down the timer and stays in the same place and keeps counting down through 3 levels. I wrote this: using UnityEngine; using System.Collections; using UnityEngine.UI;
public class countdownTimer : MonoBehaviour { public Text score; public GameObject countdownManager;
void Update()
{
DontDestroyOnLoad(countdownManager);
DontDestroyOnLoad(score);
setTime();
}
void setTime()
{
float timeSinceStart = Mathf.Round(Time.time);
float scoreText = (25 - timeSinceStart);
if (scoreText > 0) {
score.text = (scoreText.ToString());
}
else
{
score.text = ("0");
}
}
}
When switching, I got errors saying: The object of type 'Text' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
Can anyone fix the error?
Answer by JedBeryll · May 29, 2016 at 05:43 AM
Mark the score like this: DontDestroyOnLoad(score.gameObject);
I changed my code to this and it still doesn't work: using UnityEngine; using System.Collections; using UnityEngine.UI;
public class countdownTimer : $$anonymous$$onoBehaviour { public Text score; public GameObject countdown$$anonymous$$anager;
void Update()
{
DontDestroyOnLoad(countdown$$anonymous$$anager);
DontDestroyOnLoad(score.gameObject);
setTime();
}
void setTime()
{
float timeSinceStart = $$anonymous$$athf.Round(Time.time);
float scoreText = (25 - timeSinceStart);
if (scoreText > 0) {
score.text = (scoreText.ToString());
}
else
{
score.text = ("0");
}
}
}
Sorry i forgot that it's a UI element which means it most likely has a parent. As long as the parent is destroyed, it will be as well. So the proper answer should be: DontDestroyOnLoad(score.transform.root.gameObject); Or another way is to create the whole thing in the next map too and find it.
Btw you can put DontDestroyOnLoad on awake or start. You don't need to run it every frame. And like JedBeryll said, DontDestroyOnLoad() only works on objects that have no parent.
If you want you can forget about DontDestroyOnLoad and just make the values that shoudn't be erased be static, since static values don't reset when you change levels.
Your answer
Follow this Question
Related Questions
arrow from text to object - complete beginner 0 Answers
UI Text created from C# Script 0 Answers
ui Text not responding to collider 1 Answer
UI Text: Words at end of line jumping to next line 0 Answers
Add "1" to score text? Not "11111"? 1 Answer