Search Unity

Resolved Netcode: GameObject as parameter of ServerRpc Function

Discussion in 'Netcode for GameObjects' started by predows, Nov 18, 2022.

  1. predows

    predows

    Joined:
    Apr 25, 2021
    Posts:
    2
    I'm working on a multiplayer game using Netcode for GameObjects. I need to change the ownership of the car to let clients drive. This is my function:

    Code (CSharp):
    1. [ServerRpc]
    2. private void EnterCarServerRpc(GameObject net)
    3. {
    4.         Debug.Log("Start");
    5.         isDriving = true;
    6.         net.GetComponent<carController>().havePilot = true;
    7.         net.GetComponent<NetworkObject>().ChangeOwnership(OwnerClientId);
    8.         Debug.Log("SERVER: "+OwnerClientId+" is driving the car.");
    9.            
    10. }
    But the console logs this error:
    I didn't found how to do this in the documentation, so how can i fix this?
     
    mberketatar likes this.
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    In the very least, post on the Netcode for GameObjects forum. I'll move your post for you.
     
    lavagoatGG likes this.
  3. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    Since your GameObject has a NetworkObject attached, pass it as a NetworkObjectReference instead.
     
  4. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    666
    Something like this should work:
    Code (CSharp):
    1.     [ServerRpc]
    2.     private void EnterCarServerRpc(NetworkBehaviourReference carReference, ServerRpcParams serverRpcParams)
    3.     {
    4.         ulong clientId = serverRpcParams.Receive.SenderClientId;
    5.  
    6.         if (carReference.TryGet<Car>(out Car car))
    7.         {
    8.             Debug.Log("Start");
    9.             isDriving = true;
    10.             car.GetComponent<carController>().havePilot = true;
    11.             car.NetworkObject.ChangeOwnership(clientId);
    12.             Debug.Log("SERVER: " + clientId + " is driving the car.");
    13.         }
    14.         else
    15.         {
    16.             Debug.LogError("Didn't get car");
    17.         }
    18.     }
    Call it with:
    Code (CSharp):
    1.    player.EnterCarServerRpc(car, default);
     
  5. predows

    predows

    Joined:
    Apr 25, 2021
    Posts:
    2
    Thank you! Tried here and works fine :D
     
    RikuTheFuffs-U and cerestorm like this.
  6. Skngh

    Skngh

    Joined:
    Jul 3, 2020
    Posts:
    8
    How do you pass in the "NetworkBehaviourReference"? (car). How to get there from a GameObject
     
    Marmadon_ and simonleroux15 like this.