-
-
Save dzungpng/3dc5990564c4a46257c5dca7533b5148 to your computer and use it in GitHub Desktop.
Script for Mirror Networking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Mirror; | |
using System; | |
using UnityEngine; | |
using UnityEngine.UI; | |
public class ChatBehavior : NetworkBehaviour | |
{ | |
[SerializeField] private Text chatText = null; | |
[SerializeField] private InputField inputField = null; | |
[SerializeField] private GameObject canvas = null; | |
private static event Action<string> OnMessage; | |
// Called when the a client is connected to the server | |
public override void OnStartAuthority() | |
{ | |
canvas.SetActive(true); | |
OnMessage += HandleNewMessage; | |
} | |
// Called when a client has exited the server | |
[ClientCallback] | |
private void OnDestroy() | |
{ | |
if(!hasAuthority) { return; } | |
OnMessage -= HandleNewMessage; | |
} | |
// When a new message is added, update the Scroll View's Text to include the new message | |
private void HandleNewMessage(string message) | |
{ | |
chatText.text += message; | |
} | |
// When a client hits the enter button, send the message in the InputField | |
[Client] | |
public void Send() | |
{ | |
if(!Input.GetKeyDown(KeyCode.Return)) { return; } | |
if (string.IsNullOrWhiteSpace(inputField.text)) { return; } | |
CmdSendMessage(inputField.text); | |
inputField.text = string.Empty; | |
} | |
[Command] | |
private void CmdSendMessage(string message) | |
{ | |
// Validate message | |
RpcHandleMessage($"[{connectionToClient.connectionId}]: {message}"); | |
} | |
[ClientRpc] | |
private void RpcHandleMessage(string message) | |
{ | |
OnMessage?.Invoke($"\n{message}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment