Search Unity

Having problems understanding Events, SyncVars, Commands and RPCs

Discussion in 'Multiplayer' started by trinitikbonet, May 28, 2023.

  1. trinitikbonet

    trinitikbonet

    Joined:
    May 21, 2023
    Posts:
    1
    Hi, I al very new to Unity and Mirror networking and I'm having issues understanding the concepts of events, syncvars, commands and rpcs.

    For example, in trying to implement a simple chat where a new connected client is identified by a randomly generated username, I get weird behaviours where if: the host with a username [Player7864] sends a message and a new client whos username [Player 3213] connects and sends his message, the message is displayed with the proper username on the host's screen, but then when the host sends a reply message, his username becomes blank in both his screen and the new client's screen as : []: message

    Here is the ChatManager code I am using:


    using Mirror;
    using System;
    using TMPro;
    using UnityEngine;

    public class ChatManager : NetworkBehaviour
    {
    [SerializeField] private GameObject chatUI = null;
    [SerializeField] private TMP_Text chatText = null;
    [SerializeField] private TMP_InputField inputField = null;

    private static event Action<string> OnMessage;

    private string username;

    public override void OnStartAuthority()
    {
    chatUI.SetActive(true);
    GenerateUsername(); // Generate a username for the player

    OnMessage += HandleNewMessage;
    }

    [ClientCallback]
    private void OnDestroy()
    {
    if (!isOwned) { return; }

    OnMessage -= HandleNewMessage;
    }

    private void HandleNewMessage(string message)
    {
    chatText.text += message;
    }

    [Client]
    public void Send(string message)
    {
    if (!Input.GetKeyDown(KeyCode.Return)) { return; }

    if (string.IsNullOrWhiteSpace(message)) { return; }

    CmdSendMessage(message, username);

    inputField.text = string.Empty;
    }

    [Command(requiresAuthority=false)]
    private void CmdSendMessage(string message, string playerUsername)
    {
    RpcHandleMessage($"[{playerUsername}]: {message}");
    }

    [ClientRpc]
    private void RpcHandleMessage(string message)
    {
    OnMessage?.Invoke($"\n{message}");
    }

    private void GenerateUsername()
    {
    username = "Player" + UnityEngine.Random.Range(1000, 9999);
    }
    }



    This script is attached to a Player prefab GameObject with a network identity, and insode the Player prefab I have the canvas with the inputText, and chatTxt tech mesh. Can anyone guide me or give some ressources for further understanding the concepts needed for multiplayer 2d game dev, for example when commands rpcs and events are used etc.
     
  2. mischa2k

    mischa2k

    Joined:
    Sep 4, 2015
    Posts:
    4,347
    Please try our built in Examples, especially Tanks.
    That should help you get started!