Files
Test-Multiplayer/Assets/Scripts/Chat/ChatNetworkManager.cs
pelpanagiotis acd7255a88 Revert "Latest Changes"
This reverts commit 7df357342f.
2026-01-16 09:23:58 +02:00

98 lines
2.7 KiB
C#

using UnityEngine;
using Mirror;
using System.Collections.Generic;
[AddComponentMenu("")]
public class ChatNetworkManager : NetworkManager
{
[SerializeField] private GameObject chatUIPrefab;
// Server-side authoritative store of chat messages
private readonly List<string> chatMessages = new();
// Server-side map of connections to player names (moved from the old ChatUI)
internal static readonly Dictionary<NetworkConnectionToClient, string> connNames = new();
public void SetHostname(string hostname)
{
networkAddress = hostname;
}
public override void OnServerDisconnect(NetworkConnectionToClient conn)
{
if (conn.authenticationData != null)
ChatAuthenticator.playerNames.Remove((string)conn.authenticationData);
connNames.Remove(conn);
base.OnServerDisconnect(conn);
}
public override void OnClientDisconnect()
{
base.OnClientDisconnect();
// Destroy ChatUI instance when disconnecting
ChatUI existingChatUI = FindFirstObjectByType<ChatUI>();
if (existingChatUI != null)
{
Destroy(existingChatUI.gameObject);
}
// Show LoginUI again
if (LoginUI.instance != null)
{
LoginUI.instance.gameObject.SetActive(true);
LoginUI.instance.usernameInput.text = "";
LoginUI.instance.usernameInput.ActivateInputField();
}
}
public override void OnClientConnect()
{
base.OnClientConnect();
Debug.Log("ChatNetworkManager: OnClientConnect called");
// Spawn ChatUI prefab locally when client successfully connects
if (chatUIPrefab == null)
{
Debug.LogError("ChatNetworkManager: ChatUI prefab is not assigned in the inspector!");
return;
}
// Check if ChatUI already exists to avoid duplicates
ChatUI existingChatUI = FindFirstObjectByType<ChatUI>();
if (existingChatUI == null)
{
GameObject chatUIInstance = Instantiate(chatUIPrefab);
if (chatUIInstance == null)
{
Debug.LogError("ChatNetworkManager: Failed to instantiate ChatUI prefab!");
return;
}
chatUIInstance.SetActive(true);
}
// Hide LoginUI when successfully connected
if (LoginUI.instance != null)
{
LoginUI.instance.gameObject.SetActive(false);
}
}
[Server]
public void AddServerMessage(string message)
{
if (string.IsNullOrWhiteSpace(message)) return;
chatMessages.Add(message);
}
[Server]
public string[] GetHistory()
{
return chatMessages.ToArray();
}
}