软硬件交互
如何将Unity信号传送到ProtoPie
本次案例分享如何将Unity内的信号传输回到ProtoPie。

ProtoPie
August 24, 2023

素材:SocketIO for Unity
使用方法
- 在Github中下载SocketIOUnity代码

- 解压缩,然后将 SocketIOUnity 代码拖放到 Unity 项目中

- 创建新的 C# 脚本
这里我制作了一个名为 SocketIOManager 的 C# 脚本文件

- 写下代码

using System;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json.Linq;
public class SocketManager : MonoBehaviour
{
public SocketIOUnity socket;
private Rigidbody rigidBody;
private int throttling = 0;
void Start()
{
rigidBody = GetComponent<Rigidbody>(); // Load rigidBody to get car's speed
Debug.Log("Init Socket");
var uri = new Uri("<http://192.168.0.16:9981>"); // 该地址可在ProtoPie Connect界面的左下角找到
socket = new SocketIOUnity(uri);
socket.JsonSerializer = new NewtonsoftJsonSerializer();
socket.OnConnected += (sender, e) => // this function is called when socketIO is connected
{
Debug.Log("socket.OnConnected");
};
socket.OnDisconnected += (sender, e) => // this function is called when socketIO is disconnected
{
Debug.Log("disconnect: " + e);
};
socket.OnReconnectAttempt += (sender, e) => // this function is called when socketIO retries to connect to server
{
Debug.Log($"{DateTime.Now} Reconnecting: attempt = {e}");
};
Debug.Log("Connecting...");
socket.Connect();
socket.OnUnityThread("ppMessage", (data) => // 该部分用来接收来自ProtoPie的讯号
{
Debug.Log(data.ToString());
});
}
void Update()
{
if (throttling % 10 == 0) // Update function is called too frequently. so we need to restrict like this
{
socket.EmitStringAsJSON("ppMessage", '{' + "\\"messageId\\": \\"carTelemetry_speed\\"" + ',' + $"\\"value\\": \\"{rigidBody.velocity.magnitude}\\"" + '}');
throttling = 0; //该部分用来定义发送到ProtoPie的信息和数值。ppMessage是ProtoPie默认识别信息,无需修改。
}
throttling += 1;
}
void OnDestroy()
{
Debug.Log("DESTROY!!!");
}
}
- 选择‘Car’并在‘Car’中添加脚本
在检查器中拖放脚本文件

6. 运行并测试