I have made a platforming game, and have a timer in my levels. When the player completes a level, I want to be able to access this timer stored as a string and output to a text box and present it to the player. However, as the scene is finished, the time is wiped and therefore nothing is shown. How do I get it so that the time is displayed? I have already tried using a DontDestroyOnLoad, but it hasn't worked.
TimerController script - Used to operate timer:
public class TimerController : MonoBehaviour
{
public static TimerController instance;
public Text timeCounter;
private TimeSpan timePlaying;
private bool timerGoing;
private float elapsedTime;
public string timePlayingStr;
private void Awake()
{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
private void Start()
{
timeCounter.text = "Time: 00:00.00";
timerGoing = false;
BeginTimer();
}
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);
timePlayingStr = "Time: " + timePlaying.ToString("mm':'ss'.'ff");
timeCounter.text = timePlayingStr;
yield return null;
}
}
}
LoadSuccess script - Used to stop timer upon level completion:
public class LoadSuccess : MonoBehaviour
{
private TimerController GetTime;
private void OnTriggerEnter(Collider other)
{
SceneManager.LoadScene("Success");
GetTime = FindObjectOfType<TimerController>();
GetTime.EndTimer();
}
}
GetTimer script - Used to display timer once level is completed:
public class GetTimer : MonoBehaviour
{
public Text YourTime;
private TimerController GetTime;
// Start is called before the first frame update
void Start()
{
string GetTime = FindObjectOfType<TimerController>().timePlayingStr;
YourTime.text = GetTime;
}
}