问题
my question is the following: currently i have several coroutines running in my game for android/iOS but when i send the game to background in order to try other things with the phone those coroutines stop and only resume after i get back to the game; is there any way to make the coroutines continue running while the game is in background?
回答1:
Android will suspend your application by design. Co-routines run in the same thread as your Updates so making a distinction between the two in terms of running in the foreground is not too likely. Having said that there are ways around this. You could build a plugin that talks to the android platform 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. The first requiring you do something along the lines of building a plugin and the second using the following
public void OnApplicationPause(bool paused) {
if(paused) {
// Game is paused, remember the time
} else {
// Game is unpaused, calculate the time passed since the game was paused and use this time to calculate build times of your buildings or how much money the player has gained in the meantime.
}
}
for more info see this or this.
Also note that building a plugin requires a Pro Licence
Additional Co-Routine resources
- Co-Routine Execution Order
- Co-Routine Scheduler
- Deep Explaination of Co-Routines
回答2:
You can't make something permanently run in the background. The OS will event eventually pause it. Only VOIP, Media Player or GPS are allowed. Everything else only get an extended time frame until pause.
For iOS you can change "Application does not run in background" in info.plist
回答3:
Use Application.runInBackground = true;
See Unity Docs Application.runInBackground
来源:https://stackoverflow.com/questions/21287037/unity-coroutines-stop-while-in-background