Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved How can I change a player's color?

Discussion in 'Netcode for GameObjects' started by HMIMH, Oct 2, 2023.

  1. HMIMH

    HMIMH

    Joined:
    Oct 15, 2017
    Posts:
    7
    I managed to do a physics based coop prototype using network transforms and network rigidbody components, and it works good. I'm using RCP server calls for the .AddForce functions in FixedDeltaTime.

    However, how can I update player A color in realtime, so player B sees it too? I tried doing a Server RCP call, but that didn't work, it only works if I do it locally in the update. Can someone please guide me with what client/server functions do I need? Thanks in advance!
     
  2. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    677
    You can use a NetworkVariable field and change the player's colour when its value changes.

    Code (CSharp):
    1.     [SerializeField] private NetworkVariable<Color> color = new NetworkVariable<Color>();
    2.  
    3.     private void Awake()
    4.     {
    5.         color.OnValueChanged += OnColorChanged;
    6.     }
    7.  
    8.     private void OnColorChanged(Color previousValue, Color newValue)
    9.     {
    10.         // change player colour
    11.     }
     
    HMIMH likes this.
  3. HMIMH

    HMIMH

    Joined:
    Oct 15, 2017
    Posts:
    7
    Hi there! Thank you for your reply, the code works, however, only the host is able to perform the color change. The client can see it from the host, but the client cannot do it

    InvalidOperationException: Client is not allowed to write to this NetworkVariable
    Unity.Netcode.NetworkVariable
     
  4. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    677
    If you want to keep server authority you can have the client send an rpc requesting the colour change and have the server/host change it.

    You can give client authority over changing values but it isn't always recommended, you may have to put additional checks in place on the server/host that the values are acceptable. For a NetworkVariable you can give the client authority like this:
    Code (CSharp):
    1.     [SerializeField] private NetworkVariable<Color> color = new NetworkVariable<Color>(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
    Something else I should add is if you do this the server doesn't have authority to change the value, not in NGO at least.