Search Unity

How to send a float value from client to server

Discussion in 'Multiplayer' started by NocSchecter, Jun 20, 2018.

  1. NocSchecter

    NocSchecter

    Joined:
    Aug 19, 2015
    Posts:
    33
    Hello, I have a problem sending values from a client to a server in unity network.
    I have a class that sends the percentage of the battery in the client and that will be updating in the server but when I run client-server, the server does not receive data and the client shows me that:

    Trying to send command for object without authority.
    UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter, Int32, String)
    BatteryInfo:CallCmdSendBatteryValue(Single)
    BatteryInfo:Update() (at Assets/Scripts/BatteryInfo.cs:17)

    this is my code:

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Networking;
    6. public class BatteryInfo : NetworkBehaviour {
    7.     [SyncVar]
    8.     public float valorBateria;
    9.     private void Update()
    10.     {
    11.    
    12.         if (!isServer)
    13.         {
    14.             valorBateria = (SystemInfo.batteryLevel) * 100;
    15.             CmdSendBatteryValue(valorBateria);
    16.         }
    17.    
    18.     }
    19.     [Command]
    20.     public void CmdSendBatteryValue(float b)
    21.     {
    22.         RpcUpdateBaterry(b);
    23.     }
    24.     [ClientRpc]
    25.     public void RpcUpdateBaterry(float b)
    26.     {
    27.         valorBateria = b;
    28.     }
    29. }
    Am i using using the commands and RpcClient wrong?
    I am usin unity 2017
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    A Command can only be sent by the client on either a GameObject that client has been assigned authority over, or that client's Player GameObject.

    So you have 3 choices. You can move this Command to a script on the Player GameObject, assign authority of this object to that client before it needs to send the Command, or send the float using a Unet Message instead of a Command. Unet Messages are sent without association to any networked GameObject, so are ideal for instances where you don't want to be bothered with object authority.