Create random Number on server and broadcast to all clients

I’m really having trouble wrapping my head around Unity Networking. I followed the basic tutorial and have two players that can move around. Now I want to add something different: Generate a random number on the server and broadcast it to all clients. I’m able to generate the number and broadcast it, though the numbers are different on both clients:

Player1:

  • local Client: 50
  • remote Client: 37

Player2:
-remote Client: 50

  • local Client: 37

It seems to me that the number generation code is executed on the client side, even though I specified it to run only on the server. Is it wrong to attach this script to the player prefab and instead attach it to the enemy prefab as this has server authority?

You could use a SyncVar here to keep the number synced across all clients.

public class RandomNumber : NetworkBehaviour{
    [SyncVar(hook="NumberChanged")]
    int randomNumber;

    void Update(){
        // Changing the number on the update is bad, but ok for demonstrating.
        if(isServer){
            randomNumber = Mathf.FloorToInt(UnityEngine.Random.Range(0, 10));
        }

        // If you want to change it from your local player object, you can use a command
        // SyncVars should be changed from the server.
        if (Input.GetKeyDown(KeyCode.Space)){
            CmdGenerateNumber();
        }
    }

    // SyncVar hook that is invoked on all clients when the random number changes
    void NumberChanged(int _value){
        randomNumber = _value;
        print("Random number: " + randomNumber);
    }
    
    [Command]
    void CmdGenerateNumber(){
        randomNumber = Mathf.FloorToInt(UnityEngine.Random.Range(0, 10));
    }
}

If you don’t want to use a syncvar, then you might have to use networkmessages.

Thank you for your detailed answer!

1 Like