WX-Game1/Assets/Scripts/MessageHandler.cs

100 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using DefaultNamespace;
using MotionFramework;
using Newtonsoft.Json;
using UnityEngine;
// using LitJson;
/// <summary>
/// 接收来自网页的消息
/// </summary>
public class MessageHandler : MonoBehaviour
{
/// <summary>
/// 接收来自网页的消息
/// </summary>
/// <param name="message">来自网页的消息字符串</param>
public void ReceiveMessageFromWeb(string message)
{
// 打印原始消息到控制台
Debug.Log($"收到来自网页的消息: {message}");
// 尝试解析JSON消息
ParseJsonMessage(message);
}
/// <summary>
/// 解析JSON消息
/// </summary>
/// <param name="jsonMessage">JSON格式的消息字符串</param>
private void ParseJsonMessage(string jsonMessage)
{
try
{
// 使用LitJson解析JSON消息
MotionEngine.GetModule<GlobalManager>().messageData = JsonConvert.DeserializeObject<MessageData>(jsonMessage);
// 打印解析后的消息数据
Debug.Log($"成功解析JSON消息 - 代码: {MotionEngine.GetModule<GlobalManager>().messageData.code}");
// 处理解析后的消息数据
HandleParsedMessage(MotionEngine.GetModule<GlobalManager>().messageData);
}
catch (System.Exception ex)
{
// 如果JSON解析失败记录错误信息
Debug.LogError($"JSON解析失败: {ex.Message}");
Debug.LogError($"原始消息内容: {jsonMessage}");
}
}
/// <summary>
/// 处理解析后的消息数据
/// </summary>
/// <param name="messageData">解析后的消息数据</param>
private void HandleParsedMessage(MessageData messageData)
{
// 如果有code参数设置code并创建游戏模块
if (!string.IsNullOrEmpty(messageData.code))
{
Debug.Log($"正在处理消息代码: {messageData.code}");
Apis.SetCode(messageData.code);
GameLauncher.Instance.CreateGameModules();
}
// // 根据type参数执行相应的处理逻辑
// if (!string.IsNullOrEmpty(messageData.type))
// {
// Debug.Log($"正在处理消息类型: {messageData.type}");
//
// switch (messageData.type.ToLower())
// {
// case "none":
// // none: 没有任何状态,不做任何操作
// Debug.Log("消息类型为none不执行任何操作");
// break;
//
// case "sign":
// // sign: 显示签到弹窗
// Debug.Log("消息类型为sign显示签到弹窗");
// if (UIManager.Instance != null)
// {
// UIManager.Instance.ShowPage("签到");
// }
// else
// {
// Debug.LogError("UIManager实例不存在无法显示签到弹窗");
// }
// break;
//
// default:
// Debug.LogWarning($"未知的消息类型: {messageData.type}");
// break;
// }
// }
}
}