Can the counter / timer work in the background?

Is it possible to start the timer in the background. When I minimize the game, then my timer should continue, can I do it?

I tried Application.runInBackground=true; but it cannot work.

 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"); } } 
+5
source share
2 answers

I found the answer to my question. Special thanks to Mr.Dinal24. With Mr.Dinal24, I can get my answer with an update of some things, and it is very useful for me.

NOTE: THIS WORK CODE FOR ANDROID AND IOS BOTH (FOR IOS SHOULD REQUIRE UNITS 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; } } } 
+6
source

You can do it as follows:

Have a script to check if the application is minimized. To check whether the application state can be used, OnApplicationFocus .

 DateTime lastMinimize; int timer; // what ever the type you want // change the value when you game is sent to background // make sure this is changed before actual minimize happen public void aboutToMinimize(){ lastMinimize = DateTime.Now; } public void gotMaximized() { timer = (DateTime.now - lastMinimize).getMillis(); } //now use the timer value to reset the timer 
+2
source

Source: https://habr.com/ru/post/1213591/


All Articles