Unity3d-更新功能在收到MQTT消息时停止吗?

时间:2019-05-02 14:01:08

标签: c# unity3d mqtt

我正在尝试构建一个简单的MQTT应用程序。我想使用Unity在3dText中显示收到的MQTT消息。

我将字符串分配放到了Update()函数中,但是当收到一条消息时,似乎停止了Update()函数。当我在编辑器中单击某个位置时,Update()函数将唤醒并更新字符串。

C#

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Net;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using uPLibrary.Networking.M2Mqtt.Utility;
using uPLibrary.Networking.M2Mqtt.Exceptions;

using System;

public class mqttTest : MonoBehaviour {
    private MqttClient client;
    public TextMesh mytext=null;
    string msg;
    // Use this for initialization
    void Start () {

        // create client instance 
        client = new MqttClient(IPAddress.Parse("192.168.83.128"),1883 , false , null ); 

        // register to message received 
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; 

        string clientId = Guid.NewGuid().ToString(); 
        client.Connect(clientId); 


        client.Subscribe(new string[] { "test" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); 


    }

    void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) 
    { 
        msg = System.Text.Encoding.UTF8.GetString(e.Message);
        Debug.Log("Received: " + msg  );

    }


    // Update is called once per frame
    void Update () {
        Debug.Log("update");

        mytext.text = msg;

    }
}

此停止是由于开发环境还是事件机制造成的?

1 个答案:

答案 0 :(得分:0)

这可能是因为Unity仅在UnityEditor窗口(尤其是Update)处于聚焦状态时才执行PlayMode(Game view事件等)。如果在收到消息时另一个窗口具有焦点或获得焦点,则Unity会冻结直到团结编辑器Game view再次获得焦点。


您可以通过转到Player SettingsResolution and PresentationResolution启用该选项

来解决此问题。
  

在后台运行
   如果应用失去焦点,请启用此选项以使游戏保持运行(而不是暂停)。

显然,这也适用于UnityEditor本身中的播放器。

但是,仅当您的项目目标设置为“独立”或“ Web”时,它才有效/存在。


对于iOS和Android,此操作无效,因为在这些设备上,应用程序无法在后台运行。 Unity还会自动将相同的行为应用于UnityEditor本身中的播放器。

但是您仍然可以通过设置Application.runInBackground来解决它(基本上是前面提到的选项所做的事情)

  

应用程序在后台运行时,播放器是否应在运行?

     

默认值为false(应用程序在后台时暂停)。

直接从组件(附加到任何Scene GameObject)上,例如

public class EditorRunInBackground : MonoBehaviour
{
    private void Awake () 
    {
        if (Application.isEditor) Application.runInBackground = true;
    }
}

仅为UnityEditor本身设置runInBackground

或者,如果您不想将其附加到任何内容上,也可以将脚本与[RuntimeInitializeOnLoadMethod]一起使用

public static class EditorRunInBackground
{
    [RuntimeInitializeOnLoadMethod]
    private static void OnRuntimeMethodLoad()
    {
        if(Application.isEditor) Application.runInBackground = true;
    }
}

,甚至可以在Editor文件夹中播放它,因此它会在构建中被删除。