Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Create random Number on server and broadcast to all clients

Discussion in 'Multiplayer' started by christianstrang, Mar 13, 2016.

  1. christianstrang

    christianstrang

    Joined:
    Aug 6, 2013
    Posts:
    29
    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?
     
  2. sovium

    sovium

    Joined:
    Mar 8, 2016
    Posts:
    27
    You could use a SyncVar here to keep the number synced across all clients.

    Code (CSharp):
    1.  
    2. public class RandomNumber : NetworkBehaviour{
    3.     [SyncVar(hook="NumberChanged")]
    4.     int randomNumber;
    5.  
    6.     void Update(){
    7.         // Changing the number on the update is bad, but ok for demonstrating.
    8.         if(isServer){
    9.             randomNumber = Mathf.FloorToInt(UnityEngine.Random.Range(0, 10));
    10.         }
    11.  
    12.         // If you want to change it from your local player object, you can use a command
    13.         // SyncVars should be changed from the server.
    14.         if (Input.GetKeyDown(KeyCode.Space)){
    15.             CmdGenerateNumber();
    16.         }
    17.     }
    18.  
    19.     // SyncVar hook that is invoked on all clients when the random number changes
    20.     void NumberChanged(int _value){
    21.         randomNumber = _value;
    22.         print("Random number: " + randomNumber);
    23.     }
    24.    
    25.     [Command]
    26.     void CmdGenerateNumber(){
    27.         randomNumber = Mathf.FloorToInt(UnityEngine.Random.Range(0, 10));
    28.     }
    29. }
    30.  
    If you don't want to use a syncvar, then you might have to use networkmessages.
     
  3. christianstrang

    christianstrang

    Joined:
    Aug 6, 2013
    Posts:
    29
    Thank you for your detailed answer!
     
    sovium likes this.