RealTimeStrategy/Assets/Scripts/Networking/NetworkPlayer.cs

99 lines
2.1 KiB
C#

using Mirror;
using TMPro;
using UnityEngine;
public class NetworkPlayer : NetworkBehaviour
{
[Header("Connections")]
[SerializeField] private TMP_Text _playerNameObject;
[Header("Variables")]
[SyncVar(hook = nameof(SetPlayerNameTagText))]
[SerializeField]
private string _displayName = "Missing Name";
[SyncVar(hook = nameof(SetPlayerNameTagColor))]
[SerializeField]
private Color _playerColor = Color.black;
#region Server
[Server]
public void SetDisplayName(string newDisplayName)
{
_displayName = newDisplayName;
}
[Server]
public void SetPlayerColor(Color newPlayerColor)
{
_playerColor = newPlayerColor;
}
[Command]
private void CmdSetDisplayName(string newDisplayName)
{
if (NameLengthIsCorrect(newDisplayName))
{
RpcDebugLog($"Setting player names{newDisplayName}");
SetDisplayName(newDisplayName);
}
else
{
RpcDebugLog($"new name: {newDisplayName} : is too long");
}
}
[Command]
private void CmdSetNewColor()
{
Color newColor = ColorManipulation.GetRandomColor();
RpcDebugLog($"Setting player color{newColor.ToString()}");
SetPlayerColor(newColor);
}
private bool NameLengthIsCorrect(string newDisplayName)
{
return newDisplayName.Length < 10;
}
[ClientRpc]
private void RpcDebugLog(string message)
{
Debug.Log(message);
}
#endregion
#region Client
private void SetPlayerNameTagText(string oldText, string newText)
{
if (_playerNameObject != null)
{
_playerNameObject.text = newText;
}
}
private void SetPlayerNameTagColor(Color oldColor, Color newColor)
{
if (_playerNameObject != null)
{
_playerNameObject.color = newColor;
}
}
[ContextMenu("SetName")]
private void SetMyName()
{
CmdSetDisplayName("New Name");
}
[ContextMenu("NewColor")]
private void SetNewColor()
{
CmdSetNewColor();
}
#endregion
}