On a game that was made from the website “Zulama” I have attempted to get the game to reset the timer UI Object. This timer UI Object should count up the number of seconds the player was in the game for and post them on the end screen. However, the problem is when the game is played again, the end screen will also have added the timer from the previous attempts as well. I have the following code on a persistent data object that has the timer on it with a reset code that should reset the timer back to 0 on start.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PersistentData : MonoBehaviour
{
// public variables that can be set in the Inspector
// private variables
public int maxTime = 0;
public Text timerUI;
private int timer; // in seconds - how long to play
// Use this for initialization
void Start ()
{
timer = maxTime;
// make this object persistent
DontDestroyOnLoad(transform.gameObject);
InvokeRepeating ("CountUp", 1, 1);
Reset ();
}
// Update is called once per frame
void Update ()
{
}
void CountUp()
{
timer += 1;
}
public int GetTimer()
{
return timer;
}
void Reset()
{
timer = 0;
}
}
then after either the player has lost or has won the game will take them to the specified end screen where the timer is called and the timer with the number of seconds is posted using one of these scripts.
If the player won
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GetTimer2 : MonoBehaviour {
public Text timerUI;
private PersistentData persistentScript;
// Use this for initialization
void Start ()
{
persistentScript = GameObject.Find("PersistentObject").GetComponent<PersistentData>();
gameObject.GetComponent<Text> ().text = "Time Complete : " + persistentScript.GetTimer ();
timerUI.text = string.Format ("Time Completed {0:0}:{1:00}", (persistentScript.GetTimer ()) / 60, (persistentScript.GetTimer ()) % 60);
}
// Update is called once per frame
void Update ()
{
}
}
Or if the player lost
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GetTimer : MonoBehaviour {
public Text timerUI;
private PersistentData persistentScript;
// Use this for initialization
void Start ()
{
persistentScript = GameObject.Find("PersistentObject").GetComponent<PersistentData>();
gameObject.GetComponent<Text> ().text = "Time Spent : " + persistentScript.GetTimer ();
timerUI.text = string.Format ("Time Spent {0:0}:{1:00}", (persistentScript.GetTimer ()) / 60, (persistentScript.GetTimer ()) % 60);
}
// Update is called once per frame
void Update ()
{
}
}
Any help or feedback on why the timer does not reset would be greatly appreciated.