Chat System Setup
This commit is contained in:
42
Assets/Scripts/ChatBehaviour.cs
Normal file
42
Assets/Scripts/ChatBehaviour.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using Mirror;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using TMPro;
|
||||
public class ChatBehaviour : NetworkBehaviour
|
||||
{
|
||||
[SerializeField] private TextMeshProUGUI chatText = null;
|
||||
[SerializeField] private TMP_InputField inputField = null;
|
||||
[SerializeField] private GameObject canvas = null;
|
||||
|
||||
public override void OnStartClient()
|
||||
{
|
||||
canvas.SetActive(true);
|
||||
|
||||
SpawnScript.OnMessage += HandleNewMessage;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
SpawnScript.OnMessage -= HandleNewMessage;
|
||||
}
|
||||
|
||||
private void HandleNewMessage(string message)
|
||||
{
|
||||
chatText.text += message;
|
||||
}
|
||||
|
||||
[Client]
|
||||
public void Send()
|
||||
{
|
||||
if (!authority)
|
||||
{
|
||||
Debug.LogWarning("Attempted to send chat without authority.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(inputField.text)) { return; }
|
||||
NetworkClient.localPlayer
|
||||
.GetComponent<SpawnScript>()
|
||||
.CmdSendMessage(inputField.text);
|
||||
inputField.text = string.Empty;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/ChatBehaviour.cs.meta
Normal file
2
Assets/Scripts/ChatBehaviour.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3e2cbf076f9d6ec41b63cd8c0fe4c17d
|
||||
28
Assets/Scripts/SpawnScript.cs
Normal file
28
Assets/Scripts/SpawnScript.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Mirror;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
public class SpawnScript : NetworkBehaviour
|
||||
{
|
||||
public GameObject chatPrefab;
|
||||
|
||||
public static event Action<string> OnMessage;
|
||||
|
||||
public override void OnStartServer()
|
||||
{
|
||||
GameObject obj = Instantiate(chatPrefab);
|
||||
NetworkServer.Spawn(obj);
|
||||
}
|
||||
|
||||
[Command]
|
||||
public void CmdSendMessage(string message)
|
||||
{
|
||||
RpcHandleMessage($"[{connectionToClient.connectionId}]: {message}");
|
||||
}
|
||||
|
||||
[ClientRpc]
|
||||
private void RpcHandleMessage(string message)
|
||||
{
|
||||
OnMessage?.Invoke($"\n{message}");
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/SpawnScript.cs.meta
Normal file
2
Assets/Scripts/SpawnScript.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6dab1be56f31ff44889b274b8f565102
|
||||
Reference in New Issue
Block a user