I need an help with network variable (string)

I’m making my first multiplayer game. I want the player name to change and read on the screen, but
unity tells me that it is not possible to implicitly convert type ‘string’ to ‘Unity.Netcode.NetworkVariable ’. Please I need some help.
This is my code:

using UnityEngine;
using System.Collections;
using Unity.Netcode;
using Unity.Netcode.Components;
using Unity.Netcode.Transports;
using System;

public class SetupLocalPlayer : NetworkBehaviour {


    public NetworkVariable<string> pname;
    public NetworkObject cameraplace;

    void OnGUI()
    {
        if (IsLocalPlayer)
        {
            Camera.main.transform.position = cameraplace.transform.position;
            Camera.main.transform.rotation = cameraplace.transform.rotation;
            pname = GUI.TextField(new Rect(25, Screen.height - 40, 100, 30), pname);
            if (GUI.Button(new Rect(130, Screen.height - 40, 100, 30), "Change Name"))
            {
                CmdChangeName(pname);
            }
        }
    }
   
    [ServerRpc]
    public void CmdChangeName(string newName)
    {
        pname = newName;
    }

    void Start () {
        if (IsLocalPlayer)
            GetComponent<drive>().enabled = true;
    }
    void Update()
    {
        this.GetComponentInChildren<TextMesh>().text = pname.Value;
    }
}

You can no longer have a NetworkVariable of type string (although the documentation may still suggest otherwise). You can use a type such as FixedString64Bytes instead (NetworkVariable).

3 Likes

Be sure to import “using Unity.Collections” to use FixedString64Bytes

Hi @TheCreatorofSouth , as cerestorm mentioned you need to use a FixedString, like this:

using Unity.Collections;

public class SetupLocalPlayer : NetworkBehaviour
{
     NetworkVariable<FixedString128Bytes> pname = new NetworkVariable<FixedString128Bytes>();
}

The amount of bytes in the string depends on how big the string is supposed to be. 1 ASCII character = 1 byte and 1 UNICODE character = 2/3/4 bytes, so you can plan accordingly to the maximum length of your player’s name. (be mindful of oriental languages as well!)

You can use strings directly if you let Netcode know how to serialize it with UserNetworkVariableSerialization as mentioned here . There doesn’t seem to be any documentation explaining how to use it which would be useful.