using UnityEngine; using Mirror; // Networked player. This is the authority object used to run Commands. public class Player : NetworkBehaviour { [SyncVar(hook = nameof(OnNameChanged))] public string playerName; public override void OnStartServer() { playerName = (string)connectionToClient.authenticationData; } public override void OnStartLocalPlayer() { // initialize local UI var ui = FindFirstObjectByType(); if (ui != null) { ui.Initialize(this); ChatUI.localPlayerName = playerName; } // request history from server if (isLocalPlayer) CmdRequestHistory(); } void OnNameChanged(string oldName, string newName) { if (isLocalPlayer) ChatUI.localPlayerName = newName; } // Called by the local ChatUI to send a message public void SendChatToServer(string message) { if (!isLocalPlayer) return; if (string.IsNullOrWhiteSpace(message)) return; CmdSendChat(message); } // Runs on server: store message and broadcast to all clients [Command] private void CmdSendChat(string message) { var manager = NetworkManager.singleton as ChatNetworkManager; manager?.AddServerMessage($"{playerName}: {message}"); RpcReceiveChat(playerName, message); } // Runs on all clients: update local ChatUI [ClientRpc] private void RpcReceiveChat(string senderName, string message) { var ui = FindFirstObjectByType(); if (ui == null) return; var prettyMessage = senderName == ChatUI.localPlayerName ? $"{senderName}: {message}" : $"{senderName}: {message}"; ui.AddMessage(prettyMessage); } // Request history from server; server will reply with TargetReceiveHistory [Command] private void CmdRequestHistory() { var manager = NetworkManager.singleton as ChatNetworkManager; if (manager == null) return; var history = manager.GetHistory(); TargetReceiveHistory(connectionToClient, history); } // Sent only to the requesting client [TargetRpc] private void TargetReceiveHistory(NetworkConnection target, string[] history) { var ui = FindFirstObjectByType(); if (ui == null) return; ui.SetHistory(history); } }