本次內(nèi)容是講述如何將mqtt服務(wù)器中接收到的數(shù)據(jù)在Unity3D的文本框控件中顯示JSON鍵值對中的“值”。
需求:
1.GameObject——>UI——>Text (將Unity 3D的文本框控件置于場景)
命名空間引用:using UnityEngine.UI;
2.Newtonsoft插件
命名空間引用:Newtonsoft.Json.Linq;
3.MQTT通訊需求:
(1)http://www.hslcommunication.cn/ 胡工科技下載資源庫
(2)將兩個DLL文件拖入Unity的scripts文件夾(2021版本及以上的Unity不同添加Newtonsoft,不然好像會報錯,Unity已經(jīng)自帶了)
?
代碼:
using?System.Collections;
using?System.Collections.Generic;
using?UnityEngine;
using?UnityEngine.UI;
using?HslCommunication.MQTT;
using?System.Text;
using?System.Diagnostics;
using?System;
using?System.IO;
using?Newtonsoft.Json.Linq;
public?class?text_transfer?: MonoBehaviour
{
????private?MqttClient mqttClient;
????public?Text timeText; //在unity里的定義
????public?string?TimeText;
????// Start is called before the first frame update
????void?Start()
????{
????????timeText = GameObject.Find("Canvas/Text").GetComponent<Text>();
????????mqttClient = new?MqttClient(new?MqttConnectionOptions()
????????{
????????????ClientId = "ABC", ????????????????????// 客戶端的唯一的ID信息
????????????IpAddress = "192.168.1.126", ?????????????// mqtt服務(wù)器的地址
????????});
????????// 連接服務(wù)器
????????HslCommunication.OperateResult connect = mqttClient.ConnectServer();
????????if?(connect.IsSuccess)
????????{
????????????// 連接成功
????????????UnityEngine.Debug.Log("連接成功");
????????}
????????else
????????{
????????????// 連接失敗,過會就需要重新連接了
????????????UnityEngine.Debug.Log("連接失敗");
????????}
????????// 然后添加訂閱
????????HslCommunication.OperateResult sub = mqttClient.SubscribeMessage("test");
????????if?(sub.IsSuccess)
????????{
????????????// 訂閱成功
????????????UnityEngine.Debug.Log("訂閱成功");
????????}
????????else
????????{
????????????// 訂閱失敗
????????????UnityEngine.Debug.Log("訂閱失敗");
????????}
????????// 訂閱示例
????????mqttClient.OnMqttMessageReceived += (MqttClient client, string?topic, byte[] payload) =>
????????{
????????????TimeText = Encoding.UTF8.GetString(payload);
????????????UnityEngine.Debug.Log("Time:"?+ DateTime.Now.ToString());
????????????UnityEngine.Debug.Log("Topic:"?+ topic);
????????????UnityEngine.Debug.Log("Payload:"?+ Encoding.UTF8.GetString(payload));
????????????//timeText.text = TimeText;
????????};? ? ??
????}
????private?void?Update()
????{
????????string?json = TimeText;
????????JObject obj = JObject.Parse(json);
????????timeText.text = obj["轉(zhuǎn)速1"].ToString(); //將對應(yīng)鍵的數(shù)值賦值給文本框
????????UnityEngine.Debug.Log(timeText.text);//打印值的內(nèi)容在文本框
????????//UnityEngine.Debug.Log(Convert.ToInt64(timeText.text));
????}
}
1.定義文本框函數(shù)
2.接收JSON數(shù)據(jù)包
3.解析
?
4.可以用多個文本框接收對應(yīng)需求的數(shù)據(jù),或是所有數(shù)據(jù)在一個文本框顯示亦可
單文本框顯示:
?
?文章來源:http://www.zghlxwxcb.cn/news/detail-401751.html
?多文本框?qū)?yīng)顯示:多設(shè)置幾個文本框變量再照前面的重復(fù)操作下就行了文章來源地址http://www.zghlxwxcb.cn/news/detail-401751.html
到了這里,關(guān)于Unity文本框解析讀取mqtt服務(wù)器JSON數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!