c# - 如何在后台运行Unity程序?

标签 c# android unity-game-engine background

我开发了一个统一的 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 的 ContextActivity 发送到您的插件以启动该服务。您可以找到有关如何执行此操作的示例 herehere .

关于c# - 如何在后台运行Unity程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531689/

相关文章:

c# - 将 XML 文件添加到构建中

java - 如何在 Android 中将字节数组转换为 PDF 文件?

java - 在 TextView 上打印数组值(android)

android - 信号 11 (SIGSEGV),代码 1 (SEGV_MAPERR) base.apk

android - 我可以验证用户是否拥有用于在线功能的 Android 应用程序的合法副本?

c# - 什么更好 : link to a GameObject or to a Class in Unity?

c# - 尝试在 Unity 中围绕玩家生成一圈敌人

c# - TraceSource 锁定文件

c# - 在开发中使用 MySQL,在生产中使用 SQL Server

c# - 如何从代码后面打开日期选择器的日历?