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;
///
/// 单例
///
public static WebConnecter Singleton
{
get
{
if(instance == null)
{
instance = GameObject.FindObjectOfType();
if(instance == null)
{
GameObject go = new GameObject("WebConnecter");
instance = go.AddComponent();
}
}
return instance;
}
}
//引用jslib的方法
[DllImport("__Internal")]
private static extern void SendMsgToWeb(string str);
//接收数据
public Action dataHandle;
void Awake()
{
if(instance == null)
{
instance = this;
}else
{
Destroy(gameObject);
}
}
///
/// 接收web端发送数据
///
///
public void RecData(string jsonStr)
{
dataHandle?.Invoke(jsonStr);
}
///
/// 发送数据到web端
///
///
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 data = new Dictionary();
data.Add("GameState", success ? "Success" : "Fail");
data.Add("Data", "");
string json = JsonConvert.SerializeObject(data);
SendDataToWeb(json);
}
public void SendResultToWeb(bool success, double score)
{
Dictionary data = new Dictionary();
data.Add("GameState", success ? "Success" : "Fail");
data.Add("Data", score);
string json = JsonConvert.SerializeObject(data);
SendDataToWeb(json);
}
}
}