Skip to content

Instantly share code, notes, and snippets.

@dzungpng
Last active May 16, 2023 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzungpng/3dc5990564c4a46257c5dca7533b5148 to your computer and use it in GitHub Desktop.
Save dzungpng/3dc5990564c4a46257c5dca7533b5148 to your computer and use it in GitHub Desktop.
Script for Mirror Networking
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