Mqtt to Unity via

Aus hyperdramatik
Zur Navigation springen Zur Suche springen

Create yourself a namespace on

Download MQTT library from MQTT_in_Unity

Create a Unity Project (2019 version)

  • go to ASSETS --> Import Custom Pages --> Import the Mqtt Package you just downloaded to your Unity project
  • Go to Project Window --> Assets --> MQTT --> Scripts --> Test → delete TestScript. Create a new Script with the following Code (name it mqttShiftrIO):


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

public class mqttShiftrIO : MonoBehaviour

	private MqttClient client;
	public string Shiftrio_ClientID = "MyNameOnShiftIoIwant";
	public string Shiftrio_Key = "key findest du im token";
	public string Shiftrio_Secret = "langeNummer findest du unter secret im token";

	public string msg = "";

	public List<string> topics_sub = new List<string>();

	void Start () {
		// create client instance
		client = new MqttClient(IPAddress.Parse(""), 1883 , false , null ); ////////"" ---> IP from

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

		client.Connect(Shiftrio_ClientID, Shiftrio_Key, Shiftrio_Secret); 
		// subscribe to the topics in the list with QoS 2 
		foreach (String topic in topics_sub) {
			client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });


	void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) 
		string topic = e.Topic;
		msg = System.Text.Encoding.UTF8.GetString(e.Message);
		Debug.Log("Received: " + topic +" --> "+ msg);
		debug.text = msg;

	void OnGUI()//creates Button to Press
		if (GUI.Button(new Rect(20, 40, 80, 20), "Send"))
			client.Publish("hello/world", System.Text.Encoding.UTF8.GetBytes("Sending from Unity3D!!!"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
                      //"hello/world" is the topic you send the message "Sending from Unity3D!!!"

  • Create an empty game object and put the mqttShiftrIO script on it
  • go to the name space of → click on Token
  • Check your Key(Username)

Secret(Passwort) and transfer to Unity editor --> you can change the message that is shown in the inspector in the mqttShiftrIO

  • Topic subscribe → you can change the number of topics you subscribe to
  • delay (100) --> the amount of data that is send to is still in it's converting rate