Unity Webgl与JS相互交互 Unity 2021.2之后的版本

Interaction with browser scripting
When building content for the web, you might need to communicate with other elements on your web page. Or you might want to implement functionality using Web APIs which Unity doesn’t currently expose by default. In both cases, you need to directly interface with the browser’s JavaScript engine. Unity WebGL
provides different methods to do this.

Calling JavaScript functions from Unity scripts
The recommended way of using browser JavaScript in your project is to add your JavaScript sources to your project, and then call those functions directly from your script code. To do so, place files with JavaScript code using the .jslib extension under a “Plugins” subfolder in your Assets folder. The plugin file needs to have a syntax like this:

mergeInto(LibraryManager.library, {

Hello: function () {
window.alert(“Hello, world!”);
},

HelloString: function (str) {
window.alert(UTF8ToString(str));
},

PrintFloatArray: function (array, size) {
for(var i = 0; i < size; i++)
console.log(HEAPF32[(array >> 2) + i]);
},

AddNumbers: function (x, y) {
return x + y;
},

StringReturnValueFunction: function () {
var returnStr = “bla”;
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},

BindWebGLTexture: function (texture) {
GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);
},

});
Then you can call these functions from your C# scripts
like this:

using UnityEngine;
using System.Runtime.InteropServices;

public class NewBehaviourScript : MonoBehaviour {

[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);

void Start() {
    Hello();
    
    HelloString("This is a string.");
    
    float[] myArray = new float[10];
    PrintFloatArray(myArray, myArray.Length);
    
    int result = AddNumbers(5, 7);
    Debug.Log(result);
    
    Debug.Log(StringReturnValueFunction());
    
    var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);
    BindWebGLTexture(texture.GetNativeTexturePtr());
}

}
后边直接看官方文档里边的里边就可以了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值