I want to create a timer that runs at all times even when the app is closed. I want a timer that can do this so that after 30 minutes a life is replenished. I also want to display this timer with GUI. How can I do this? I know how to create a timer with some code that I will post here, but I do not know how to run it at all times. Also with this code when I call CreateClock() for some reason the clock does not show. Is there a better way to do this?
using UnityEngine;
using System.Collections;
public class ClockScript : MonoBehaviour {
public bool clockIsPaused;
public float startTime; //(in seconds)
public float timeRemaining; //(in seconds)
public bool timeIsUp;
public string timeStr;
//Screen sizes
public int sixthOfScreenW;
public int sixthOfScreenH;
public GUIStyle labelStyle;
public bool displayed;
private bool start;
public void CreateClock (){
sixthOfScreenW = Screen.width / 6;
sixthOfScreenH = Screen.height / 6;
clockIsPaused = false;
timeIsUp = false;
startTime = Time.time + 61.0f;
displayed = true;
start = true;
}
void OnGUI (){
if (displayed) {
labelStyle.fontSize = Screen.width / 20;
GUI.Label ( new Rect(sixthOfScreenW * 4, sixthOfScreenH * 0.5f, sixthOfScreenW, sixthOfScreenH * 0.5f), timeStr, labelStyle);
}
}
void Update (){
if (start) {
if (!clockIsPaused)
{
// make sure the timer is not paused
DoCountdown();
}
}
}
void DoCountdown (){
timeRemaining = startTime - Time.time;
if (timeRemaining < 0)
{
timeRemaining = 0;
clockIsPaused = true;
TimeIsUp();
}
ShowTime();
}
public void PauseClock (){
clockIsPaused = true;
}
public void UnpauseClock (){
clockIsPaused = false;
}
void ShowTime (){
int minutes;
int seconds;
minutes = (int)timeRemaining/60;
seconds = (int)timeRemaining%60;
timeStr = "Time: " + minutes.ToString() + ":";
timeStr += seconds.ToString("D2");
}
void TimeIsUp (){
timeIsUp = true;
}
}