Hello fellow Unity users
I’m currently working on a car game, I have two scenes (a main menu and a game) and I would like to have a timer on my main game HUD.
My main menu contains a PLAY button that loads the next scene, and my game contains a pause menu with a RESTART button that reloads the scene in order to restart the level from the beginning.
public void RestartGame() //This is the button that restarts the level
{
Time.timeScale = 1.0f; //this is so that the level isn't paused when the scene is reloaded
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
The timer is supposed to be started by a Manager script given below. I want the timer to start as soon as the scene is loaded or reloaded, and to stop whenever the cube has travelled forward 50 units.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Manager : MonoBehaviour
{
[SerializeField]
private TimerController timerController;
[SerializeField]
private MovingCube cube;
void Start()
{
timerController.BeginTimer();
}
// Update is called once per frame
void Update()
{
if (cube.transform.position.z > 50)
{
timerController.EndTimer();
}
}
}
Below is the TimerController script used to display the time on the HUD :
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class TimerController : MonoBehaviour
{
public static TimerController instance;
[SerializeField]
private TMP_Text timeCounter;
private TimeSpan timePlaying;
private bool timerGoing;
private float elapsedTime;
private void Awake()
{
instance = this;
}
void Start()
{
timeCounter.text = "00:00.00";
timerGoing = false;
}
public void BeginTimer()
{
timerGoing = true;
elapsedTime = 0f;
StartCoroutine(UpdateTimer());
}
public void EndTimer()
{
timerGoing = false;
}
private IEnumerator UpdateTimer()
{
while (timerGoing)
{
elapsedTime += Time.deltaTime;
timePlaying = TimeSpan.FromSeconds(elapsedTime);
string timePlayingStr = timePlaying.ToString("m':'ss'.'fff");
timeCounter.text = timePlayingStr;
yield return null;
}
}
}
I don’t get why my timer won’t start, I tried to change the Manager script and use Awake or OnEnable but it didn’t work… I sometimes manage to get the timer to start once but never when I reload the scene…
I used scripts I found online for the TimerController so there might be better ways to create a timer
Any ideas ?
Thanks, Guillaume