Can i run timer in background.
When i minimize game then my timer should be works continue can i do ?
I was try Application.runInBackground=true;
but it can’t works.
public class Counter : MonoBehaviour
{
public Text counterText;
private int counterValue;
// Use this for initialization
void Start ()
{
Application.runInBackground=true;
StartCoroutine ("StartCounter");
}
IEnumerator StartCounter ()
{
yield return new WaitForSeconds (1f);
counterText.text = "Counter : " + counterValue.ToString ();
counterValue++;
StartCoroutine ("StartCounter");
}
}
I have found answer of my question.
NOTE : THIS CODE WORKS FOR ANDROID AND IOS BOTH (FOR IOS MUST REQUIRED UNITY 4.6.1 OR ABOVE)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class Counter : MonoBehaviour
{
public Text counterText, pauseText, resumeText, msgText;
private int counterValue, focusCounter, pauseCounter;
private DateTime lastMinimize;
private double minimizedSeconds;
void OnApplicationPause (bool isGamePause)
{
if (isGamePause) {
pauseCounter++;
pauseText.text = "Paused : " + pauseCounter;
GoToMinimize ();
}
}
void OnApplicationFocus (bool isGameFocus)
{
if (isGameFocus) {
focusCounter++;
resumeText.text = "Focused : " + focusCounter;
GoToMaximize ();
}
}
// Use this for initialization
void Start ()
{
StartCoroutine ("StartCounter");
Application.runInBackground = true;
}
IEnumerator StartCounter ()
{
yield return new WaitForSeconds (1f);
counterText.text = "Counter : " + counterValue.ToString ();
counterValue++;
StartCoroutine ("StartCounter");
}
public void GoToMinimize ()
{
lastMinimize = DateTime.Now;
}
public void GoToMaximize ()
{
if (focusCounter >= 2) {
minimizedSeconds = (DateTime.Now - lastMinimize).TotalSeconds;
msgText.text = "Total Minimized Seconds : " + minimizedSeconds.ToString ();
counterValue += (Int32)minimizedSeconds;
}
}
}
Coroutines run in the same thread as your function Update(). If you use target platform as Android, you could build a plugin. Or use OnApplicationPause and calculate the time passed in the application and do whatever it is you were wanting to do in the time frame between.
void OnApplicationPause(bool paused) {
if(paused) {
//Save the time
} else {
//Recalculate the time
}
}
I hope that it will help you.
If you want your game to run in background constantly I would suggest you to go to Player Settings and make sure “Run in Background” is checked.