Unity Render Streaming通过Js与Unity自定义通讯
Js通讯发送示例在WebApp\client\public\videoplayer;
对应C#接收端案例Unity Render Streaming插件的WebBrowserInput
JS发送部分
videoplayer/js/main.js按钮通讯示例
const elementBlueButton = document.createElement('button');
elementBlueButton.id = "blueButton";
elementBlueButton.innerHTML = "Light on";
playerDiv.appendChild(elementBlueButton);
elementBlueButton.addEventListener("click", function () {
sendClickEvent(videoPlayer, 1);
});
案例只能发送一个按钮Number ID 往上溯源,在js/register-events.js文件中的sendClickEvent函数
export function sendClickEvent(videoPlayer, elementId) {
let data = new DataView(new ArrayBuffer(3));
data.setUint8(0, InputEvent.ButtonClick);
data.setInt16(1, elementId, true);
videoPlayer && videoPlayer.sendMsg(data.buffer);
}
核心代码
videoPlayer.sendMsg(data.buffer);
data.setUint8(0, InputEvent.ButtonClick);
data.setInt16(1, elementId, true);
查看案例已经定义的所有通讯类型
const InputEvent = {
Keyboard: 0,
Mouse: 1,
MouseWheel: 2,
Touch: 3,
ButtonClick: 4,
Gamepad: 5,
};
我们新增加一个发送字符串的通讯类型,定义标签为 6
function sendMessage(videoPlayer, message) {
function utf8FromStr(str) {
var strUtf8 = unescape(encodeURIComponent(str));
var arr = new Uint8Array(strUtf8.length);
for (var i = 0; i < strUtf8.length; ++i) {
arr[i] = strUtf8.charCodeAt(i);
}
return arr;
}
message = " " + message;
var buf = utf8FromStr(message);
let data = new DataView(buf.buffer);
data.setUint8(0, 6);
videoPlayer && videoPlayer.sendMsg(data.buffer);
}
function sendJson(videoPlayer, json) {
sendMessage(videoPlayer, JSON.stringify(json));
}
C#接收部分
Unity Streaming Render示例的WebBrowserInputChannelReceiver是接收webRtc数据通讯的通道(channel),继承自InputChannelReceiverBase类。WebBrowserInputChannelReceiver通过消息注册获取标签类型为4的ButtonClick事件 我们的目标是自定义字符串(JSON)通讯,默认基类不会处理自定义类型。 从派生一个新类,直接继承OnMessage接收二进制数据流函数,OnMessage收到的字节流就是JS中sendMsg发送的二进制原始数据 代码如下:
public class DBBrowserInputChannelReceiver : WebBrowserInputChannelReceiver
{
public GameObject[] targets;
protected override void OnMessage(byte[] bytes)
{
if (bytes.Length > 0)
{
int code = bytes[0];
if (code == 6)
{
string message = System.Text.UTF8Encoding.UTF8.GetString(bytes, 1, bytes.Length - 1);
foreach (GameObject go in targets)
{
go.SendMessage("OnNetMessage", message);
}
if (code <= 5)
{
base.OnMessage(bytes);
}
}
}
}
}
|