Petition-to-the-Gods-V3/Assets/Scripts/Client/ClientMessageHandler.cs
2025-11-18 05:08:27 +08:00

128 lines
4.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 UnityEngine;
using Mirror;
using System;
public class ClientMessageHandler : MonoBehaviour
{
public static ClientMessageHandler Instance;
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
public void RegisterHandler()
{
NetworkClient.RegisterHandler<GameMessage>(OnServerMessageReceived);
}
public void UnregisterHandler()
{
NetworkClient.UnregisterHandler<GameMessage>();
}
void OnServerMessageReceived(GameMessage msg)
{
Debug.Log($"¦¬¨ì Server °T®§: {msg.action} {msg.payload}");
try
{
switch (msg.action)
{
case "welcome":
{
switch(msg.payload)
{
case "hello":
Debug.Log("Welcome °T®§ÅçÃÒ¦¨¥\");
// clean data
ClientWorkMessageHandleSceneController.cleanData();
ClientWorkMessageHandleSceneController.messageResultCount = 0;
ClientLastWordsSceneController.words = "";
if (ClientHomeWaittingSceneController.Instance != null)
{
ClientHomeWaittingSceneController.Instance.OnWelcomeMessageReceived();
}
break;
}
}
break;
case "workMessageResult":
{
if (ClientWorkMessageHandleSceneController.Instance != null)
{
GameMessageWorkResult resultObj = JsonUtility.FromJson<GameMessageWorkResult>(msg.payload);
ClientWorkMessageHandleSceneController.messageResultCount = resultObj.count;
if (resultObj != null)
{
ClientWorkMessageHandleSceneController.Instance.onReceiveResult(resultObj.result, resultObj.resultText);
}
else
{
Debug.LogError("workMessaggeResult failed");
}
}
}
break;
case "gameFinalWords":
{
if (string.IsNullOrEmpty(ClientLastWordsSceneController.words))
{
ClientLastWordsSceneController.words = msg.payload;
if (ClientGameBackToRealSceneController.Instance)
{
StartCoroutine( ClientGameBackToRealSceneController.Instance.LoadNextScene());
}
}
}
break;
case "gameTalkingStart":
{
if (ClientGameTalkingSceneController.Instance)
{
ClientGameTalkingSceneController.Instance.processStep(2);
}
}
break;
case "gameTalkingGodSay":
{
if (ClientGameTalkingSceneController.Instance)
{
ClientGameTalkingSceneController.Instance.onReceivedChatMessage(msg.payload);
}
}
break;
}
}
catch (Exception e)
{
Debug.LogError($"¸ÑªR JSON ¥¢±Ñ: {e.Message}");
}
}
public void SendMessageToServer(string action, string message)
{
if (NetworkClient.isConnected)
{
GameMessage msg = new GameMessage { action = action, payload = message };
NetworkClient.Send(msg);
Debug.Log($"µo°e°T®§¨ì Server: {message}");
}
else
{
Debug.LogError($"µo°e°T®§¨ì Server ¥¢±Ñ: {message}");
}
}
}