Countdown Timer Not Resetting on Game Load

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
duolazhang
Posts: 10
Joined: Fri Oct 06, 2023 10:54 am

Countdown Timer Not Resetting on Game Load

Post by duolazhang »

Hi Tony,

I’m having trouble with the countdown timer in my game.

The countdown timer script:

using TMPro;
using UnityEngine;
using UnityEngine.Events;

public class CountdownTimer : MonoBehaviour
{
public float countdownTime;
public TMP_Text countdownText;
public UnityEvent onCountdownFinished;

private float currentTime;
private bool isCountingDown;
private static CountdownTimer instance;

private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
return;
}
}

private void Start()
{
ResetTimer();
}

private void Update()
{
if (isCountingDown)
{
currentTime -= Time.deltaTime;
UpdateCountdownUI();

if (currentTime <= 0)
{
isCountingDown = false;
onCountdownFinished.Invoke();
}
}
}

private void UpdateCountdownUI()
{
int minutes = Mathf.FloorToInt(currentTime / 60);
int seconds = Mathf.FloorToInt(currentTime % 60);
int milliseconds = Mathf.FloorToInt((currentTime * 100) % 100);

countdownText.text = string.Format("{0:00}:{1:00}:{2:00}", minutes, seconds, milliseconds);
}

public void StartCountdown()
{
ResetTimer();
isCountingDown = true;
}

public void ResetTimer()
{
currentTime = countdownTime;
UpdateCountdownUI();
}

It works fine during gameplay and restarts correctly with OnRestartGame(). However, when I save and then load the game, the timer doesn’t reset and continues counting down.

In the dialogue system, node sequence window, I activate the timer using:

SetActive(3MinsCounDownText, true);
SendMessage(StartCountdown, , 3mins_CountdownTimer);

Do you have any ideas on how to fix this so the timer resets properly when loading a saved game?

Thanks!
User avatar
Tony Li
Posts: 22093
Joined: Thu Jul 18, 2013 1:27 pm

Re: Countdown Timer Not Resetting on Game Load

Post by Tony Li »

Hi,

I recommend making your script into a custom Saver. To do this, inherit from Saver instead of MonoBehaviour:

Code: Select all

public class CountdownTimer : Saver
Then implement the methods RecordData() and ApplyData(string). In RecordData(), return a string that encodes the values of currentTime and isCountingDown. In ApplyData(), use the string to set those variables again.

For more info, please see: https://pixelcrushers.com/phpbb/viewtopic.php?f=9&t=4763
Post Reply