You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.6 KiB

using UnityEngine;
using System;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace EduCoderTool
{
/*
* web端通讯中转器
* @author lz
**/
public class WebConnecter : MonoBehaviour
{
private static WebConnecter instance = null;
/// <summary>
/// 单例
/// </summary>
public static WebConnecter Singleton
{
get
{
if(instance == null)
{
instance = GameObject.FindObjectOfType<WebConnecter>();
if(instance == null)
{
GameObject go = new GameObject("WebConnecter");
instance = go.AddComponent<WebConnecter>();
}
}
return instance;
}
}
//引用jslib的方法
[DllImport("__Internal")]
private static extern void SendMsgToWeb(string str);
//接收数据
public Action<string> dataHandle;
void Awake()
{
if(instance == null)
{
instance = this;
}else
{
Destroy(gameObject);
}
}
/// <summary>
/// 接收web端发送数据
/// </summary>
/// <param name="jsonStr"></param>
public void RecData(string jsonStr)
{
dataHandle?.Invoke(jsonStr);
}
/// <summary>
/// 发送数据到web端
/// </summary>
/// <param name="data"></param>
public void SendDataToWeb(string data)
{
Debug.LogFormat(">>>>>> unity send web data{0}",data);
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
SendMsgToWeb(data);
}
}
public void SendResultToWeb(bool success)
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("GameState", success ? "Success" : "Fail");
data.Add("Data", "");
string json = JsonConvert.SerializeObject(data);
SendDataToWeb(json);
}
public void SendResultToWeb(bool success, double score)
{
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("GameState", success ? "Success" : "Fail");
data.Add("Data", score);
string json = JsonConvert.SerializeObject(data);
SendDataToWeb(json);
}
}
}