Search Unity

Question how to give every player their own variable that everyone else sees?

Discussion in 'Netcode for GameObjects' started by KristenBoyGames, May 20, 2022.

  1. KristenBoyGames

    KristenBoyGames

    Joined:
    May 23, 2021
    Posts:
    38
    can someone give me an example of code that lets every clients player have their own variable (like their name) and have it so that everyone else sees them the same as the client sees them. i know it is probably very simple but i have no idea how to do it.
     
  2. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    Code (CSharp):
    1. private string playerName="";
    2.  
    3. private void SetMyName(string name) {//call this as the local player
    4.     if (!IsLocalPlayer) return; //don't want others to change our name
    5.     playerName=name;
    6.     SetMyNameServerRpc(playerName);
    7. }
    8.  
    9. [ServerRpc]
    10. private void SetMyNameServerRpc(string name) { //called on the server's version of *this* player object
    11.     if (!IsLocalPlayer) playerName=name;
    12.     SetPlayerNameClientRpc(playerName);
    13. }
    14.  
    15. [ClientRpc]
    16. private void SetPlayerNameClientRpc(string name) { //called on the other clients' version of *this* player object
    17.     if (!IsLocalPlayer && !IsServer) playerName=name;
    18. }
    Note that the ifs in the ServerRpc and ClientRpc are to avoid doing the same thing twice (since the server may also be a player and the calling player is also a client).
     
  3. KristenBoyGames

    KristenBoyGames

    Joined:
    May 23, 2021
    Posts:
    38
    i attached it to the playerobjects and made the playername var public and when i look in the editor both playerobjects have the same playername (every client sees the other players playername as the playername that their player has)
     
  4. ClearDark

    ClearDark

    Joined:
    Aug 25, 2013
    Posts:
    14
    [SerializeField]
    public NetworkVariable<ForceNetworkSerializeByMemcpy<FixedString64Bytes>> playerName = new NetworkVariable<ForceNetworkSerializeByMemcpy<FixedString64Bytes>>();


    Call server rpc to set it. Make sure that on each client, on each "player" object Update, you set the var's name to the correct one. That way every client see's every others updated network var.
     
  5. KristenBoyGames

    KristenBoyGames

    Joined:
    May 23, 2021
    Posts:
    38
    it says that the type of namespace could not be found. what is the name of the 'using something' (idk what its called). Also could there be a problem with all the playerobjects having the same name, if yes then how do i change them?
     
  6. KristenBoyGames

    KristenBoyGames

    Joined:
    May 23, 2021
    Posts:
    38
    nevermind it works, the problem was that i didn't put the if
    (!IsLocalPlayer) return;
    in the update where i set the playername to
    playerName = PlayerPrefs.GetString("SavedUsername");