需求背景
最近微信广告要求微信小游戏必须接入广告归因js-sdk, 但我们的unity开发的微信小游戏游戏逻辑都在c#实现, 所以需要JS与C#的通信, 全网搜索之前还没有其他同学对此做过总结分享, 借此水一篇小作文
C#发消息给JS
js库代码
在unity工程Plugins文件夹里创建wx.jslib
mergeInto(LibraryManager.library, {
CSharpSendMsgToJS: function (msgPtr) {
// 注意window系统jslib文件不能添加中文注释, 否则会打包失败
// 用于将 Unity 中的字符串指针转换为 JavaScript 字符串
var msg = _WXPointer_stringify_adaptor(msgPtr);
console.log(msg);
// 在js里创建一个方法接收c#的消息
window.handleReceiveMsgFromCSharp(msg);
}
});
c#桥接代码
public class Bridge : MonoBehaviour
{
private static Bridge _instance;
[DllImport("__Internal")]
private static extern void CSharpSendMsgToJS(string msg);
public void JSSendMsgToCSharp(string msg)
{
Debug.Log($"CSharp收到了JS发来的消息: {msg}");
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
public static void Init()
{
if (_instance == null)
{
GameObject go = GameObject.Find("WXBridge");
if (go == null)
{
go = new GameObject("WXBridge");
DontDestroyOnLoad(go);
}
_instance = go.AddComponent<Bridge>();
}
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("msg", "hello form CSharp");
CSharpSendMsgToJS(JsonConvert.SerializeObject(data));
}
}
JS发消息给C#
function sendMsgToCSharp(data) {
GameGlobal.Module.SendMessage(
// 注意此字符串必须与GameObject的名称保持一致
'WXBridge',
'JSSendMsgToCSharp',
JSON.stringify(data)
)
}
GameGlobal.Module.SendMessage方法的实现在unity打包的微信小游戏工程里根目录下的webgl.wasm.framework.unityweb.js里
function SendMessage(gameObject, func, param) {
var func_cstr = stringToNewUTF8(func);
var gameObject_cstr = stringToNewUTF8(gameObject);
var param_cstr = 0;
try {
if (param === undefined) _SendMessage(gameObject_cstr, func_cstr);
else if (typeof param === "string") {
param_cstr = stringToNewUTF8(param);
_SendMessageString(gameObject_cstr, func_cstr, param_cstr);
} else if (typeof param === "number") _SendMessageFloat(gameObject_cstr, func_cstr, param);
else throw "" + param + " is does not have a type which is supported by SendMessage.";
} finally {
_free(param_cstr);
_free(gameObject_cstr);
_free(func_cstr);
}
}