当前位置: 首页 > news >正文

Unity WebGL、js发布交互

官网参考
Unity3D开发之WebGL平台上 unity和js前端通信交互

在这里插入图片描述
在这里插入图片描述

WebFun.jslib

mergeInto(LibraryManager.library, {JSLog: function (str) { var strs=UTF8ToString(str); Log(str); Log(strs);}, Hello: function () {var strs="Hello, world!"; Log(strs); Log(UTF8ToString(strs)); }, HelloString: function (str) { Log(str); Log(UTF8ToString(strs)); }, PrintFloatArray: function (array, size) { var strs="";for(var i = 0; i < size; i++){var data =   HEAPF32[(array >> 2) + i]; strs+=data;if(i!=size-1){strs+=",";}}  Log(strs); Log(UTF8ToString(strs)); }, AddNumbers: function (x, y) { var data = x + y; Log(data); Log(UTF8ToString(data)); return data;}, StringReturnValueFunction: function () {var returnStr = "bla";var bufferSize = lengthBytesUTF8(returnStr) + 1;var buffer = _malloc(bufferSize);stringToUTF8(returnStr, buffer, bufferSize); Log(buffer);Log(UTF8ToString(buffer)); return buffer;}, BindWebGLTexture: function (texture) { GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);var strs="BindWebGLTexture";Log(strs);Log(UTF8ToString(strs)); 	}, 
});

unitywebdata.js


// 网页端 JavaScriptvar  gameInstance function setgameInstance( gameIn)
{ LogTip("setgameInstance 33 :");gameInstance = gameIn;LogTip("setgameInstance 333 :"+(gameInstance==null||gameInstance==undefined));
}function LogTip(str)
{// console.log(str); window.alert(str);
}function Log(str)
{  SendToUnity(str)
}function SendToUnity(message) {//发送消息给unity //第一个参数:挂在脚本的物体 //第二个参数:unity被调用的函数 //第三个参数:函数传入的参数gameInstance.SendMessage('Demo', 'JSCallUnity', message);
}function SetFunPos(cname, cvalue, exdays) {   //exdays表示天数var d = new Date();d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));var expires = "expires=" + d.toGMTString(); document.cookie = cname + "=" + cvalue + "; " + expires;LogTip(`SetFunPos\r\ncname=${cname}:${cvalue};${exdays}\r\ncname=${cname}:${cvalue};${expires}` );
}function GetFunPos (cname) {var returnArg;    //传出去的参数var name = cname + "=";var ca = document.cookie.split(';');for (var i = 0; i < ca.length; i++) {var c = ca[i].trim();if (c.indexOf(name) == 0) {returnArg = c.substring(name.length, c.length);LogTip(`GetFunPos\r\ncname=${cname}:${returnArg}` );//gameInstance.SendMessage("Test", "ReciveCookieMsg", returnArg);//发送消息给unity //第一个参数:挂在脚本的物体 //第二个参数:unity被调用的函数 //第三个参数:函数传入的参数gameInstance.SendMessage('Demo', 'JSCallUnityRespone', returnArg);return; // returnArg;}}return "";
}
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;public class UnityWebCtrl : MonoBehaviour
{#region WebFun.jslib//This Log method is the one written by the front end// Several methods can be added here. Remember to separate the methods with commas.// Otherwise, an error will be reported when packaging on the WebGL platform//When packaging, there cannot be any Chinese characters in jslib. Annotations are not acceptable either. Otherwise, this error will be reported.//Building Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js failed with output:[DllImport("__Internal")]private static extern void Hello();[DllImport("__Internal")]private static extern void HelloString(string str);[DllImport("__Internal")]private static extern void PrintFloatArray(float[] array, int size);[DllImport("__Internal")]private static extern int AddNumbers(int x, int y);[DllImport("__Internal")]private static extern string StringReturnValueFunction();[DllImport("__Internal")]private static extern void BindWebGLTexture(int texture);[DllImport("__Internal")]private static extern void JSLog(string str); //此处传入的类型和调用时候传入的数据类型一定要一致#endregionvoid Start(){AddText( "********************");}private void Update(){if (Input.GetKeyDown(KeyCode.O)){UnityCallJs();}if (Input.GetKeyDown(KeyCode.P)){ UnityCallJs_old(); }if (Input.GetKeyDown(KeyCode.K)){AddText($"***456asd123***");}}void UnityCallJs_old(){ int num = System.DateTime.Now.Second;AddText($"SetFunPos:{num}");Application.ExternalCall("SetFunPos", "PosX", num);AddText($"GetFunPos:{num}");Application.ExternalCall("GetFunPos", "PosX");}void UnityCallJs(){ AddText($"***456艾斯黛拉看123***");string msg = null;AddText($"Reqset  Hello:");Hello();msg = "This is a string.";AddText($"Reqset  HelloString:{msg}");HelloString(msg);float[] myArray = new float[10];AddText($"Reqset  PrintFloatArray:");PrintFloatArray(myArray, myArray.Length);AddText($"Reqset  AddNumbers:5,7");int result = AddNumbers(5, 7);AddText($"Respone  AddNumbers:{result}");AddText($"Reqset  StringReturnValueFunction:");msg = StringReturnValueFunction();AddText($"Respone  StringReturnValueFunction:{msg}");AddText($"Reqset  BindWebGLTexture:");var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);BindWebGLTexture(texture.GetNativeTextureID());AddText($"Reqset  JSLog:");JSLog("666");}public void JSCallUnity(string msg)//web js 回调{AddText($"JSCallUnity Receive:{msg}");}public  void JSCallUnityRespone(string str) //web js 回调{  AddText($"JSCallUnityRespone Receive:{str}");}[SerializeField] private Text text;private void AddText(string value){if (text == null)return;text.text += $"[{System.DateTime.Now.ToString()}]:{value}\r\n"  ;}
}

index.html 补充

<script>var buildUrl = "Build";var loaderUrl = buildUrl + "/demoTests.loader.js";var config = {dataUrl: buildUrl + "/demoTests.data",frameworkUrl: buildUrl + "/demoTests.framework.js",codeUrl: buildUrl + "/demoTests.wasm",streamingAssetsUrl: "StreamingAssets",companyName: "DefaultCompanyTest",productName: "EnhanceScrollView",productVersion: "1.1",showBanner: unityShowBanner,};var canvas = document.querySelector("#unity-canvas")function loadScript(url, callback) { var script = document.createElement("script"); script.type = "text/javascript";  script.src = url; script.onload = callbackdocument.head.appendChild(script); }; createUnityInstance(canvas, config, (progress) => {}).then((unityInstance) => { // window.alert("setgameInstance 00");loadScript("unitywebdata.js", (script2)=> {// window.alert("setgameInstance 11"); // script2.setgameInstance(unityInstance);//Errorvar fun = setgameInstance; //引用abc函数fun(unityInstance); }); }); </script>

IIS web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration><system.webServer><staticContent><remove fileExtension=".mem" /><remove fileExtension=".data" /><remove fileExtension=".unity3d" /><remove fileExtension=".jsbr" /><remove fileExtension=".membr" /><remove fileExtension=".databr" /><remove fileExtension=".unity3dbr" /><remove fileExtension=".jsgz" /><remove fileExtension=".memgz" /><remove fileExtension=".datagz" /><remove fileExtension=".unity3dgz" /><remove fileExtension=".json" /><remove fileExtension=".unityweb" /><mimeMap fileExtension=".mem" mimeType="application/octet-stream" /><mimeMap fileExtension=".data" mimeType="application/octet-stream" /><mimeMap fileExtension=".unity3d" mimeType="application/octet-stream" /><mimeMap fileExtension=".jsbr" mimeType="application/octet-stream" /><mimeMap fileExtension=".membr" mimeType="application/octet-stream" /><mimeMap fileExtension=".databr" mimeType="application/octet-stream" /><mimeMap fileExtension=".unity3dbr" mimeType="application/octet-stream" /><mimeMap fileExtension=".jsgz" mimeType="application/x-javascript; charset=UTF-8" /><mimeMap fileExtension=".memgz" mimeType="application/octet-stream" /><mimeMap fileExtension=".datagz" mimeType="application/octet-stream" /><mimeMap fileExtension=".unity3dgz" mimeType="application/octet-stream" /><mimeMap fileExtension=".json" mimeType="application/json; charset=UTF-8" /><mimeMap fileExtension=".unityweb" mimeType="application/octet-stream" /><mimeMap fileExtension=".ab" mimeType="application/octet-stream" /><mimeMap fileExtension=".br" mimeType="application/octet-stream" />  <!-- <mimeMap fileExtension=".wmv" mimeType="application/octet-stream" /> --></staticContent><directoryBrowse enabled="true" /><httpProtocol><customHeaders><add name="Access-Control-Allow-Credentials: " value="true" /><add name="Access-Control-Allow-Headers" value="Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time" /><add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" /><add name="Access-Control-Allow-Origin" value="*" /></customHeaders></httpProtocol></system.webServer>
</configuration>

相关文章:

  • Oracle OCP认证考试考点详解083系列11
  • 什么是先验?(CVPR25)Detail-Preserving Latent Diffusion for Stable Shadow Removal论文阅读
  • 面试题 03.06 动物收容所
  • Node.js入门指南:开启JavaScript全栈开发之旅
  • C++从入门到实战(十三)C++函数模板与类模板初阶讲解
  • CentOS 7 基础环境安装脚本
  • Milvus 向量数据库详解与实践指南
  • linux(centos)联网情况下部署
  • 【Prometheus】业务指标与基础指标的标签来源差异及设计解析
  • 堆与二叉树——C语言
  • 鸿蒙开发——3.ArkTS声明式开发:构建第一个ArkTS应用
  • Python爬虫(20)Python爬虫数据存储技巧:二进制格式(Pickle/Parquet)性能优化实战
  • 康养休闲旅游住宿服务实训室:构建产教融合新标杆
  • Flowable7.x学习笔记(二十一)查看我的发起
  • 【ArcGIS Pro微课1000例】0068:Pro原来可以制作演示文稿(PPT)
  • 国产Word处理控件Spire.Doc教程:在Java中为Word文本和段落设置边框
  • 使用 Celery + Redis + Eventlet 实现 Python 异步编程(Windows 环境)
  • Python爬虫实战:获取百度学术专题文献数据并分析,为读者课题研究做参考
  • VRM Add-on for Blender 学习笔记
  • 第7章-3 维护索引和表
  • 重温经典|开播20周年,仙剑的那些幕后你知道吗?
  • 中国科协发声:屡禁不止的奇葩论文再次敲响学风建设警钟
  • 保证断电、碰撞等事故中车门系统能够开启!隐藏式门把手将迎来强制性国家标准
  • 暴雨蓝色预警:南方开启较强降雨过程
  • 关税风暴下,3G资本拟94亿美元私有化美国鞋履巨头斯凯奇,溢价30%
  • 山东滕州车祸致6人遇难,肇事司机已被刑事拘留