How to change scenes when time hits zero
Asked Answered
N

1

0

I’ve been able to make a countdown timer for my game but have been unable to set it up so that when the timer ends/ hits zero, it switches to a game over scene.

Here’s the time script that I’m working with:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Countdown : MonoBehaviour
{
	public float timeStart = 60;
	public Text textBox;
	
	void Start()
	{
		textBox.text = timeStart.ToString();
	}
	
	void Update()
	{
		timeStart -= Time.deltaTime;
		textBox.text = Mathf.Round(timeStart).ToString();
	}
}

Help would be much appreciated :slight_smile:

Neutralization answered 16/6, 2023 at 7:53 Comment(0)
P
0
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Countdown : MonoBehaviour
{
    [SerializeField] int timeOnStart = 60;
    [SerializeField] Text textBox;
    [SerializeField] string sceneName = "> scene name goes here <";
    int _counter;
    
    void OnEnable()
    {
        textBox.text = $"Time Left: --";
        ClockStart();
    }
  
    void OnDisable ()
    {
        ClockStop();
    }
  
    public void ClockStart ()
    {
        _counter = timeOnStart;
        UpdateText();
        InvokeRepeating(
            nameof(ClockTick) ,
            1f ,// the very first tick after 1 second
            1f// 1 second between every tick
        );
    }
  
    public void ClockStop ()
    {
        CancelInvoke( nameof(ClockTick) );
    }
  
    void ClockTick ()
    {
        _counter--;
        UpdateText();
  
        if( _counter<=0 )
        {
            ClockStop();
            SceneManager.LoadScene( sceneName );
        }
    }
  
    void UpdateText ()
    {
        textBox.text = $"Time Left: {Mathf.Round(_counter)}";
    }
    
}
Positivism answered 15/6, 2023 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.