vue项目接入unity3D模块并进行数据通信

2 篇文章 0 订阅

vue项目接入unity3D模块并进行数据通信

unity项目端

  1. 定义一个后缀名为 .jslib 文件,名字随意起,但是一定要放在Plugins文件夹,代码示例如下
 mergeInto(LibraryManager.library, {             //固定格式
  SendToHTML: function (unityData) {            //自定义函数 发送数据到Vue项目
	 strs = Pointer_stringify(unityData);
	 GetUnityEvent(strs);
	},	
  ReportReady : function () {
    window.ReportReady();
  },
});

可参考一下官方文档WebGL: Interacting with browserscripting,官方文档的说明蛮详细的。

  1. 在unity编辑器中,新建名为GameRoot空物体,挂上GameRoot.cs脚本。代码如下:
using UnityEngine;
using System.Runtime.InteropServices;
using System;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Collections;

public class GameRoot : MonoBehaviour
{
    #region 公开属性

    public JsonData currData;
    #endregion
    public Text showTxt;
    #region   DllImport
    [DllImport("__Internal")]
    private static extern string ReportReady();

    [DllImport("__Internal")]
    private static extern void SendToHTML( string unityData);
    #endregion
    void Start()
    {
    }
    public void Update()
    {
    	//测试
        if (Input.GetKeyUp(KeyCode.S))
        {
            currData = new JsonData
            {
                cmd = "unityTest",
                SingleDataList = new List<SingleData>  {
                    new SingleData {name ="test0",data ="001"},
                    new SingleData {name ="test1",data ="002"},
                    new SingleData {name ="test2",data ="001"},
                    new SingleData {name ="test3",data ="002"},
                    new SingleData {name ="test4",data ="001"},
                }
            };
            GetHTMLEvent(JsonSerialize(currData));
        }
    }

    /// <summary>
    /// 传递给html的方法
    /// </summary>
    public void SendToHTML_onClick()
    {
        currData = new JsonData()
        {
            cmd = "unityTest",
            SingleDataList = new List<SingleData>  {
                new SingleData {name ="test0",data ="001"},
                new SingleData {name ="test1",data ="002"},
            }
        };
        string _str = JsonSerialize(currData);
        print(_str);
        SendToHTML(_str);
    }
    /// <summary>
    /// 从html传递过来的方法
    /// </summary>
    /// <param name="str"></param>
    public void GetHTMLEvent(string json)
    {
        JsonData _data = JsonDeserialize(json);
        showTxt.text = json;
        print(json);
    }
    //序列化
    private string JsonSerialize(System.Object obj)
    {
        return JsonUtility.ToJson(obj);
    }
    //反序列化
    private JsonData JsonDeserialize(string str)
    {
        return JsonUtility.FromJson<JsonData>(str);
    }
}

[System.Serializable]
public class JsonData
{
    public string cmd;
    public List<SingleData> SingleDataList;
}
[System.Serializable]
public class SingleData
{
    public string name;
    public string data;
}
  1. unity打包webgl,同时修改打包后的index.html文件,在 script 标签中添加
//接收unity发来的消息
function  GetUnityEvent(unityData){   //unity中设置的方法名称
    window.top.dispatchEvent(new CustomEvent('unityEvent',{detail:{'unityData':unityData}}))//自定义事件,然后获取相应的数据
  };
  //发送消息到unity
  function SendToUnity(obj){
    // unityInstance.SendMessage("objectName","methodName","value");
    unityInstance.SendMessage("GameRoot","GetHTMLEvent",JSON.stringify(obj));
  };

vue项目端

  1. 把unity打包后的文件放在vue项目中的public文件夹下面。在vue页面中使用 iframe 标签引入:
 <iframe 
     ref="unityIframe" 
     src="/unityWebgl/index.html" 
     frameborder="0" 
     width="100%" 
     height="100%">       
  </iframe>
  1. 在vue页面中加入:
mounted() {
    window.addEventListener('unityEvent', this.unityWatch)
    this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('unityEvent', this.unityWatch)
    })
},
methods: {
    //发送消息
    Send2Unity() {
        // console.log('myData:',this.myData)
        this.$refs.iframeDom.contentWindow.SendToUnity({
            cmd: 'test',
            SingleDataList: [
                {
                    name: '2',
                    data: '2',
                }
            ]
        })
    },
    //接收消息
    unityWatch(obj) {
        console.log('obj:', obj.detail)
    }
}

Tips:

  • Unity打包webgl 网页全屏,将
 <body>
    <div class="webgl-content">
      <div id="unityContainer" style="width: 1900px; height: 960px"></div>`
    </div>
  </body> 

修改为

<body scroll="no" style="overflow-y:hidden">
    <div class="webgl-content" style="width: 100%; height: 100%">
        <div id="unityContainer" style="width: 100%; height: 100%; </div>
    </div>
 </body> 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值