1
\$\begingroup\$

In my game you have 2 minutes to finish the whole game and after searching for an answer to my problem I think I should use DontDestroyOnLoad but I can't understand how to use it correctly. Here's the code:

public class countdownTimer : MonoBehaviour {

    public float myTimer = 120;
    public Text timerText;
    private bool timerIsActive = true;

    void Start () {
        timerText = GetComponent<Text> ();
    }

    void Update () {
        if (timerIsActive) {
            myTimer -= Time.deltaTime;
            timerText.text = myTimer.ToString ("f0");
            print (myTimer);

            if (myTimer <= 0) {
                myTimer = 0;
                timerIsActive = false;
                SceneManager.LoadScene ("lose");

            }
        }

    }
}
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

You can just put the line in the Unity API of DontDestroyOnLoad() inside Awake() method and your object will not get destroyed when you load a new scene. This does mean that you need to manage the object separately or use a Find() method to find and access it in later scenes. Keep in mind that if you include this object in all your scenes, you will end up with duplicates.

In your case, to make this object persist through scenes, you can just change your code like so:

public class countdownTimer : MonoBehaviour {

    public float myTimer = 120;
    public Text timerText;
    private bool timerIsActive = true;

    void Start () {
        timerText = GetComponent<Text> ();
    }

    void Awake() {
        DontDestroyOnLoad(transform.gameObject);
    }

    void Update () {
        if (timerIsActive) {
            myTimer -= Time.deltaTime;
            timerText.text = myTimer.ToString ("f0");
            print (myTimer);

            if (myTimer <= 0) {
                myTimer = 0;
                timerIsActive = false;
                SceneManager.LoadScene ("lose");

            }
        }

    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .