Question by
pixed · Mar 25 at 11:55 PM ·
unityeditor
Unity android OnApplicationPause timer countdown don't work
hi i have a sample script to learn time in unity, one as stopwatch and one for timer countdown made with same origin scrip, the OnApplicationPause run good for stopwatch but not running for timer countdown
script is here
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System;
public class Timer : MonoBehaviour { bool timerActive = false; float currentTime; public int startMinutes; public Text currentTimeText; bool isStarted; DateTime pauseDateTime; // Start is called before the first frame update void Start() { currentTime = startMinutes * 60; }
// Update is called once per frame
void Update()
{
if (timerActive == true)
{
currentTime -= Time.deltaTime;
isStarted = true;
if (currentTime <= 0)
{
timerActive = false;
Start();
Debug.Log("Timer finished!");
}
}
TimeSpan time = TimeSpan.FromSeconds(currentTime);
currentTimeText.text = time.Minutes.ToString() + ":" + time.Seconds.ToString();
}
private void OnApplicationPause(bool isPaused)
{
if (isStarted)
{
if (isPaused)
{
// when paused
pauseDateTime = DateTime.Now;
}
else
{
//when resumed
currentTime -= (int)(DateTime.Now - pauseDateTime).TotalSeconds;
}
}
}
public void StartTimer()
{
timerActive = true;
}
public void StopTimer()
{
timerActive = false;
}
}
Comment