Hi All,
I could really use some help. I’m updating an android app i’ve made and I want to add a sleep timer function for users to fall asleep to audio.
I’ve got my audio able to run in background using Android Native Audio plugin.
But I just can’t get the timer to work out of focus or on pause. I don’t need to keep track of the time I just need it to run out. I’ve tried a few variations of co-routines but still getting nowhere.
Here is my working script:
using UnityEngine;
using UnityEngine.UI;
public class CountdownTimer : MonoBehaviour
{
public float timeRemaining = 60;
public Slider slider;
public Text TimerText;
public Text RunningTimer;
public bool timerIsRunning;
private void Start()
{
timerIsRunning = false;
}
void Update()
{
if (timerIsRunning)
{
slider.value = timeRemaining;
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
DisplayTime(timeRemaining);
}
else
{
timeRemaining = 0;
timerIsRunning = false;
GameObject.Find("AUDIOPANEL").GetComponent<TestAudioManager>().StopAudio();
}
}
}
//I'm not sure what to do with the update method when i'm trying to use onapplicationpause/focus....please help.
public void DisplayTime(float DisplayTime)
{
DisplayTime += 1;
float minutes = Mathf.FloorToInt(DisplayTime / 60);
float seconds = Mathf.FloorToInt(DisplayTime % 60);
TimerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
RunningTimer.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
public void SetTime(float value)
{
string sliderMessage = Mathf.Round(slider.value / 60) + ":00";
TimerText.text = sliderMessage;
RunningTimer.text = sliderMessage;
}
public void StartTimer()
{
timerIsRunning = true;
timeRemaining = slider.value;
}
public void StopTimer()
{
timerIsRunning = false;
}
}