当前位置:网站首页>Unity render streaming communicates with unity through JS
Unity render streaming communicates with unity through JS
2022-07-03 13:33:00 【foenix66】
Unity Render Streaming adopt Js And Unity Custom communication
Js The example of communication sending is in WebApp\client\public\videoplayer;
Corresponding C# Receiver case Unity Render Streaming The plug-in WebBrowserInput
JS Send part
videoplayer/js/main.js Example of button communication
const elementBlueButton = document.createElement('button');
elementBlueButton.id = "blueButton";
elementBlueButton.innerHTML = "Light on";
playerDiv.appendChild(elementBlueButton);
elementBlueButton.addEventListener("click", function () {
sendClickEvent(videoPlayer, 1);
});
A case can only send one button Number ID
Go back to the source , stay js/register-events.js In the document sendClickEvent function
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);
}
Core code
videoPlayer.sendMsg(data.buffer); // This is a binary array sending function , Theoretically, any data can be sent .
data.setUint8(0, InputEvent.ButtonClick); // The first field of the binary array is 1 Type mark of bytes
data.setInt16(1, elementId, true); // The data after the first byte is interpreted differently according to the label type definitions , Turn here to 2 Bytes of short type , For buttons id
View all communication types defined in the case
const InputEvent = {
Keyboard: 0,
Mouse: 1,
MouseWheel: 2,
Touch: 3,
ButtonClick: 4,
Gamepad: 5,// The case defines 0-5 Mark , Corresponding to mouse, keyboard, game console , Communicate with buttons
};
We add a new communication type for sending strings , Define the label as 6
function sendMessage(videoPlayer, message) {
function utf8FromStr(str) {
var strUtf8 = unescape(encodeURIComponent(str)); // UTF8 Encode text to binary
var arr = new Uint8Array(strUtf8.length);
for (var i = 0; i < strUtf8.length; ++i) {
arr[i] = strUtf8.charCodeAt(i);
}
return arr;
}
message = " " + message; // Leave a space as the first byte , Storage type label 6
var buf = utf8FromStr(message);
let data = new DataView(buf.buffer);
data.setUint8(0, 6); // Custom tag 6 Replace the first reserved space character
videoPlayer && videoPlayer.sendMsg(data.buffer); // Send binary data string
}
function sendJson(videoPlayer, json) {
// You can also send customized Json Format text data
sendMessage(videoPlayer, JSON.stringify(json));
}
C# Receiving part
Unity Streaming Render Example WebBrowserInputChannelReceiver It's reception webRtc Data communication channel (channel), Inherited from InputChannelReceiverBase class .WebBrowserInputChannelReceiver The tag type obtained through message registration is 4 Of ButtonClick event
Our goal is to customize the string (JSON) Communications , The default base class does not handle custom types .
Derive a new class from , Direct inheritance OnMessage Receive binary data stream function ,OnMessage The byte stream received is JS in sendMsg Binary raw data sent
The code is as follows :
public class DBBrowserInputChannelReceiver : WebBrowserInputChannelReceiver
{
public GameObject[] targets;
protected override void OnMessage(byte[] bytes)
{
if (bytes.Length > 0)
{
int code = bytes[0]; // The first byte is the communication type mark
if (code == 6) // Our custom string communication type tag
{
string message = System.Text.UTF8Encoding.UTF8.GetString(bytes, 1, bytes.Length - 1); // Remove the first marked byte of the data stream , The remaining bytes pass UTF8 Encoding is converted back to string , Corresponding JS Of UTF8 Coding function unescape(encodeURIComponent(str))
foreach (GameObject go in targets)
{
go.SendMessage("OnNetMessage", message); // Pass the data through Unity Of SendMessage Send to processing node
}
if (code <= 5)
{
base.OnMessage(bytes); // Process default type messages through base classes
}
}
}
}
}
边栏推荐
- Today's sleep quality record 77 points
- Introduction to the implementation principle of rxjs observable filter operator
- Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
- The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti
- Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
- SQL Injection (POST/Search)
- In the promotion season, how to reduce the preparation time of defense materials by 50% and adjust the mentality (personal experience summary)
- 实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
- 研发团队资源成本优化实践
- [today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay
猜你喜欢
Introduction to the implementation principle of rxjs observable filter operator
[email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g"/>
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
Annotation and reflection
Libuv Library - Design Overview (Chinese version)
STM32 and motor development (from MCU to architecture design)
8皇后问题
AI 考高数得分 81,网友:AI 模型也免不了“内卷”!
使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例
常见的几种最优化方法Matlab原理和深度分析
Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?
随机推荐
Spark实战1:单节点本地模式搭建Spark运行环境
Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)
Universal dividend source code, supports the dividend of any B on the BSC
json序列化时案例总结
Smbms project
18W word Flink SQL God Road manual, born in the sky
MyCms 自媒体商城 v3.4.1 发布,使用手册更新
The reasons why there are so many programming languages in programming internal skills
MySQL installation, uninstallation, initial password setting and general commands of Linux
开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
这本数学书AI圈都在转,资深ML研究员历时7年之作,免费电子版可看
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values
用户和组命令练习
When we are doing flow batch integration, what are we doing?
Libuv库 - 设计概述(中文版)
Mobile phones and computers can be used, whole people, spoof code connections, "won't you Baidu for a while" teach you to use Baidu
php:&nbsp; The document cannot be displayed in Chinese
显卡缺货终于到头了:4000多块可得3070Ti,比原价便宜2000块拿下3090Ti
Reptile
R语言gt包和gtExtras包优雅地、漂亮地显示表格数据:nflreadr包以及gtExtras包的gt_plt_winloss函数可视化多个分组的输赢值以及内联图(inline plot)