Mutual calls between Unity and JavaScript

1. Unity calls Js

1. Create a new suffix in the Unity project: .jslib file
insert image description here
insert image description here
2. Write the unity call js code in the .jslib file. Remember to use multiple methods, separated by numbers, otherwise an error will be reported when packaging.

mergeInto(LibraryManager.library,{
    
    
	UpdateDatabaseScore:function(score1,score2,score3,score4,score5,score6,totalscore)
	{
    
    
		// js端写好的函数
	    updateStudentScore(score1,score2,score3,score4,score5,score6,totalscore);
	},
	
	H5TTS:function(content){
    
    
	    // 在Unity中向js传递字符串时需要在js中使用Pointer_stringify(str)进行转换。
	    h5Tts(Pointer_stringify(content));
	}
	
});

3. Call in c# code

    [DllImport("__Internal")]
    public static extern void UpdateDatabaseScore(float score1,float score2,float score3,float score4,float score5,float score6,float totalscore);
    [DllImport("__Internal")]
    public static extern void H5TTS(string content);

	/// <summary>
    /// unity 调用js 端进行更新数据
    /// </summary>
    /// <param name="score1"></param>
    /// <param name="score2"></param>
    /// <param name="score3"></param>
    /// <param name="score4"></param>
    /// <param name="score5"></param>
    /// <param name="score6"></param>
    /// <param name="totalscore"></param>
    public void UpdateDBScore(float score1,float score2,float score3,float score4,float score5,float score6,float totalscore)
    {
    
    
#if !UNITY_EDITOR
        UpdateDatabaseScore(score1,score2,score3,score4,score5,score6,totalscore);
#endif
    }

    /// <summary>
    /// 由于Unity在webgl平台下请求百度token时会出现跨域问题,故在h5端进行语音合成
    /// </summary>
    /// <param name="content"></param>
    public void SendTTS(string content)
    {
    
    
        Debug.Log("Send txt"+content);
#if !UNITY_EDITOR
        H5TTS(content);
#endif
    }

2. Js calls Unity
1. Call C# code in js

gameInstance.SendMessage("GameCtrl","OnTTSComplete",allTime);

2. Code executed in C#

	/// <summary>
    /// 语音合成结束的H5端调用
    /// </summary>
    /// <param name="isSuccess"></param>
    public void OnTTSComplete(float time)
    {
    
    
        Debug.Log("js调用成功:"+time);
        EventCenter.Broadcast<float>(EventDefine.OnTTSComplete,time);
    }

Guess you like

Origin blog.csdn.net/weixin_41743629/article/details/117127583