Unity 调用 H5
本文使用的 unity 版本为:2021.3.3
1.在unity中通过c#的特性DllImport导出外部实现函数
csharp
[DllImport("__Internal")]
private static extern void callJsString(string param);
[DllImport("__Internal")]
private static extern void callJsInt(int param);
[DllImport("__Internal")]
private static extern void callJsFloat(float param);
[DllImport("__Internal")]
private static extern void callJsBoolean(bool param);
2.在unity的Plugins文件夹(没有则创建一个)里面创建一个后缀为.jslib的文件
3.在xxx.jslib文件中实现函数,如下
javascript
mergeInto(LibraryManager.library, {
callJsString: function (param) {
console.log(Pointer_stringify(param));
},
callJsInt: function (param) {
console.log(param);
},
callJsFloat: function (param) {
console.log(param);
},
callJsBoolean: function (param) {
console.log(param);
},
});
注意: 使用传参字符串的时候,使用Pointer_stringify转下字符串,否则可能会报错或者乱码
4.如果想要调用.js里面的接口或者.html里面的方法,可以通过往window里面注册函数进行调用的方式
例如:在index.html里面注册函数 window.httpPost = httpPost;
javascript
<script>
function httpPost(url, params) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
let data = xhr.response;
console.log("Status: " + xhr.status + " " + xhr.statusText + " data: " + data);
success(data);
}
else if (xhr.status >= 400) {
console.log("Status: " + xhr.status + " " + xhr.statusText);
fail(xhr.status, xhr.statusText)
}
}
console.log("Status: Send Post Request to " + url);
xhr.open("POST", url, true);
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.timeout = 10000;
xhr.send(params);
}
window.httpPost = httpPost;
</script>
5.可以在xxx.jslib文件中调用index.html里面的httpPost函数,当时也可以直接把函数实现直接放在xxx.jslib文件中
javascript
mergeInto(LibraryManager.library, {
callJsString: function (url,params) {
window.httpPost(Pointer_stringify(url),Pointer_stringify(params));
},
});
6.上面的方式可以让我们在案例httpPost调用其他位置的.js代码或者其他位置的插件
H5调用 Unity
1.这里的方式主要是在index.html文件中在创建unityInstance的时候通过缓存unityInstance并向unityInstance发送消息的方式实现
2.在index.html中创建unityInstance的时候缓存unityInstance
这里通过:window.unityInstance = unityInstance; 缓存了unityInstance实例
javascript
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
window.unityInstance = unityInstance;
}).catch((message) => {
alert(message);
});
};
3.向unity发送消息
gameobjectName:接收消息的gameobject名
funcName:方法名
param:参数,字符串,可以传json
javascript
function sendUnityMessage(gameobjectName,funcName,param)
{
if(window.unityInstance)
{
window.unityInstance.SendMessage(gameobjectName,funcName,param);
}
}