我开发了一个统一的 android 应用程序。我想在应用程序处于前台和后台时执行一些操作。现在我正在尝试以递归方式在几个时间间隔内打印日志。我正在使用这种方法来调用我的倒数计时器。
void OnApplicationFocus(bool hasFocus){
StartBattle();
isPaused = !hasFocus;
Debug.Log("isPaused " + isPaused);
}
void OnApplicationPause(bool pauseStatus){
isPaused = pauseStatus;
StartBattle();
}
并且这个方法以递归的方式打印数据。
public void StartBattle(){
StartCoroutine(BattleRecursive(0));
}
public IEnumerator BattleRecursive(int depth){
// Start Coroutine"
yield return new WaitForSeconds(2f);
if (depth == 0)
yield return StartCoroutine(BattleRecursive(depth + 1));
if (depth == 1)
yield return StartCoroutine(BattleRecursive(depth + 1));
Debug.Log("MyCoroutine is now finished at depth " + depth);
}
当应用程序在前台时,日志打印得很好,但是当应用程序在后台时,它不打印任何东西。
最佳答案
当 Unity 退出时,您无法在后台执行 Unity C# 代码。您要在后台运行的这段代码必须用 Java 编写。
用 Java 而不是 C# 编写您想执行的代码,然后使用 Android 的 Intent
启动服务。这需要您将当前 Unity 的 Context
或 Activity
发送到您的插件以启动该服务。您可以找到有关如何执行此操作的示例 here和 here .
关于c# - 如何在后台运行Unity程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531689/