I have been trying to learn how to use mirror to make a simple chat. I have been running into authority issues for the command. My script is the same as the tutorial but it is a bit a old.
I have a networkmanger on one object and a network identity and this script on another
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using Mirror;
using TMPro;
public class Chat : NetworkBehaviour
{
public TMP_Text textOutPut;
public TMP_InputField inputText;
private static event Action<string> OnMessage;
public override void OnStartAuthority()
{
OnMessage += HandleNewMessage;
}
[ClientCallback]
private void OnDestroy()
{
if (!hasAuthority) { return; }
OnMessage -= HandleNewMessage;
}
private void HandleNewMessage(string message)
{
Debug.Log("recieve message");
textOutPut.text += message;
}
[Client]
public void Send(string message)
{
if (string.IsNullOrWhiteSpace(message)) { return; }
if(hasAuthority)
CmdSendMessage(message);
}
[Client]
public void Send()
{
Debug.Log("calling send");
if (string.IsNullOrWhiteSpace(inputText.text)) { return; }
//if(hasAuthority)
// CmdSendMessage(inputText.text);
CmdSendMessage(inputText.text);
inputText.text = string.Empty;
}
[Command]
private void CmdSendMessage(string message)
{
Debug.Log("calling cmd");
RpcHandleMessage($"[{connectionToClient.connectionId}]: {message}");
}
[ClientRpc]
private void RpcHandleMessage(string message)
{
Debug.Log("calling rpc");
OnMessage?.Invoke($"\n{message}");
}
}
I gather I don’t have the authority to call CmdSendMessage but I don’t how I should be doing this properly/how to fix the error.
I tried using if(hasauthority) but then it gives me no error but doesn’t call the command.
I think some of my issues stem from the player object this is attached to not being spawned by the network manager. Now that I have changed it to do that it kind of works and the last connected client can send to themselves but not to anyone else. If I connect another client they get that power.
One more edit. I have figured the last connected client ends up with authority. I don’t know how to give authority back to the previously connected clients I think it my problem.
It works if i replace [command] with [Command(ignoreAuthority = true)] but I assume that isn’t how you are meant to do it!