Unity WebGL、js发布交互

发布于:2025-05-08 ⋅ 阅读:(21) ⋅ 点赞:(0)

官网参考
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


// 网页端 JavaScript

var  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); //此处传入的类型和调用时候传入的数据类型一定要一致
     
    
    #endregion
    
    void 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 = callback
		document.head.appendChild(script); 
    }; 
   
	createUnityInstance(canvas, config, (progress) => {
	
	}).then((unityInstance) => { 
		// window.alert("setgameInstance 00");
		loadScript("unitywebdata.js", (script2)=> {
			// window.alert("setgameInstance 11"); 
			// script2.setgameInstance(unityInstance);//Error
			var 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>

网站公告

今日签到

点亮在社区的每一天
去签到