【问题标题】:Unity3d - Update function stops when MQTT message is received?Unity3d - 收到 MQTT 消息时更新功能停止?
【发布时间】:2019-05-03 17:39:49
【问题描述】:

我正在尝试构建一个简单的 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;

    }
}

这个停止是由于开发环境还是事件机制?

【问题讨论】:

    标签: c# unity3d mqtt


    【解决方案1】:

    这可能是因为 Unity 只执行 PlayMode(Update 事件等),而 UnityEditor 窗口,特别是 Game view 被聚焦。如果另一个窗口在收到您的消息时获得焦点,Unity 会冻结,直到 Unity 编辑器的 Game view 再次获得焦点。


    您可以通过转至 Player Settings → 来解决此问题Resolution and Presentation → Resolution启用 选项

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

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

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


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

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

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

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

    直接来自组件(附加到任何场景游戏对象),例如

    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 文件夹中播放它,这样它就会在构建中被剥离。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多