Search Unity

Using command and RPC to rotate non player object

Discussion in 'Multiplayer' started by meghaksh4footprints, May 29, 2019.

  1. meghaksh4footprints

    meghaksh4footprints

    Joined:
    Mar 5, 2019
    Posts:
    2
    I have a non player server object(a cube) which is spawned whenever the server is getting started and visible to all the clients who joins that server.

    If I interact with the cube from server, it is visible to all the clients. But the reverse is not happening. I want my clients to interact with cube and everyone including server should be able to see it.

    I came to know that it is possible with command and RPC but don't know how exactly I can implement it. Any reference will be of great help.

    Thanks,
    Meghaksh
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    With Unet you can send the Command to rotate the cube from the client to the server on that client's Player GameObject, or you can use Unet Messages to tell the server to rotate the object.
     
  3. dontdiedevelop

    dontdiedevelop

    Joined:
    Sep 18, 2018
    Posts:
    68
    Code (CSharp):
    1. Quaternion targetRotation;
    2. void Update(){
    3. transform.rotation = targetRotation;
    4.  
    5.  if(Input.GetKeyDown(KeyCode.Mouse0)
    6.  {
    7.    Quaternion newRotation = transform.rotation; //target rotation
    8.    if(isServer)
    9.      RpcSetRotation(newRotation); //set rotation
    10.    else
    11.      CmdSetRotation(newRotation); //set rotation
    12.  }
    13. }
    14.  
    15. [Command]
    16. void CmdSetRotation(Quaternion newRotation)
    17. {
    18. RpcSetRotation(newRotation);
    19. }
    20.  
    21. [ClientRPC]
    22. void RpcSetRotation(Quaternion newRotation)
    23. {
    24. targetRotation = newRotation;
    25. }