Nicknames in multiplayer

I’ve some problems with nicknames creating in multiplayer.

Can anybody give me a clue how do i have to do it?

Basically it’s done like this:

  • When a client joins or changes it’s nickname he has to send it via RPC to all other players.
  • The server (which is also a player) stores the names for each player.
  • When new client connects, the server sends a nickname update only to this new player for every other player the server has on his list.

Now it depends on where you store the nicknames. When each player has a player object, it’s probably the easiest to store it in a variable of a script on that object.

That’s how a player script could look like. Each player object needs of course a NetworkView and in this case it’s owned by the respective player.

//C#
using UnityEngine;

public class PlayerObject : MonoBehaviour
{
    private string m_NickName = "";

    void Start()
    {
        // maybe reload the last used name from PlayerPrefs or generate a random name
        BroadcastNickName();
    }

    public void BroadcastNickName()
    {
        networkView.RPC("UpdateNickName", RPCMode.All, m_NickName);
    }

    public void SendNickNameTo(NetworkPlayer aPlayer)
    {
        networkView.RPC("UpdateNickName", aPlayer, m_NickName);
    }

    public void ChangeNick(string aNewNickName)
    {
        if (!networkView.isMine)
            return; // We can only change the nick when we are the owner of this player object
        m_NickName = aNewNickName;
        BroadcastNickName();
    }

    [RPC]
    void UpdateNickName(string aNewNickName)
    {
        if (networkView.isMine)
            return; // We don't want others to change our nickname
        m_NickName = aNewNickName;
    }
}

On the server you would have a manager class which holds a list of all connected players and their player objects:

//C#
using UnityEngine;
using System.Collections.Generic;

public class Manager : MonoBehaviour
{
    private List<PlayerObject> m_Players = new List<PlayerObject>();
    void OnPlayerConnected(NetworkPlayer aPlayer)
    {
        foreach(PlayerObject P in m_Players)
            P.SendNickNameTo(aPlayer);
    }
}

Of course the Manager has to keep his m_Player list up to date, so when a player object is created he has to add it to the list and when he leaves he has to remove it.

When ever a client wants to change his nick, just use ChangeNick();

It depends on how and where the Player objects are created. Maybe you have to do the SendNickNameTo calls a bit later when the new client is ready to receive all nicknames.