如何在后台运行Unity程序

如何在后台运行Unity程序

本文介绍了如何在后台运行Unity程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个统一的android应用程序.我想在应用程序处于前台和后台时执行一些操作.现在,我正在尝试以递归方式在几个时间间隔内打印日志.我正在使用此方法调用倒数计时器.

I have developed an unity android application. I want to perform some action when app is in foreground and also in background. Right now i am trying to print log in several interval of time in recursive manner. I am using this method to call my countdown timer.

void OnApplicationFocus(bool hasFocus){
        StartBattle();
        isPaused = !hasFocus;
        Debug.Log("isPaused " + isPaused);
    }

void OnApplicationPause(bool pauseStatus){
      isPaused = pauseStatus;
      StartBattle();
     }

这种以递归方式打印数据的方法.

And this method to print data in a recursive manner.

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);
    }

当应用程序位于前台时,日志打印效果很好,但是当应用程序位于后台时,它没有打印任何内容.

Log is printing very well when app is in foreground, But when app is in background, it is not printing anything.

推荐答案

退出Unity后,您将无法在后台执行Unity C#代码.您要在后台运行的这段代码必须使用Java制作.

You can't execute your Unity C# code in the background when Unity exit. This code you want to run in the background must be made in Java.

用Java而不是C#编写要在Java中执行的代码,然后使用Android的Intent启动服务.这要求您将当前Unity的ContextActivity发送到您的插件才能启动该服务.您可以在此处找到有关如何执行此操作的示例和此处.

Write the code you want to Execute in Java not in C# then use Android's Intent to start a service. This requires that you send current Unity's Context or Activity to your plugin in order to start the service. You can find examples on how to do that here and here.

这篇关于如何在后台运行Unity程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:01