Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Should I use networkObjectID or networkObjectRefrence when refrencing a network object.

Discussion in 'Netcode for GameObjects' started by IStealKneeCaps, Jul 30, 2023.

?

Which method would you use?

  1. Using ID

    1 vote(s)
    50.0%
  2. Using NetworkObjectRefrence

    1 vote(s)
    50.0%
  3. Or another way

    0 vote(s)
    0.0%
  1. IStealKneeCaps

    IStealKneeCaps

    Joined:
    Oct 8, 2017
    Posts:
    2
    My friend and I are trying to make a multiplayer game.
    And I have discovered 2 ways in general to send a networkObject via a serverRPC. I am unsure which way is best or if there is a better alternative.

    The first is solution i found was using the NetworkObjects
    .NetworkObjectId
    variable. With this I can send the ID in a ServerRPC and then access the NetworkObject, small example:
    Code (CSharp):
    1. [ServerRpc]
    2. void ToggleObjectServerRpc(bool state, ulong ID)
    3. {
    4.     NetworkManager.SpawnManager.SpawnedObjects[ID].gameObject.SetActive(state);
    5. }
    The other way I found is by using a NetworkObjectRefrence which is the one I see online the most:
    Code (CSharp):
    1. [ServerRpc]
    2. void ToggleObjectServerRpc(bool state, NetworkObjectReference refrence)
    3. {
    4.     NetworkObject netObj = refrence.TryGet();
    5.     netObj.gameObject.SetActive(state);
    6. }
    Generally I see the latter option the most when I google this question, but I haven't found an answer. I would think sending a ulong over the internet is faster than sending an entire struct. Which one should I prefer using. Or is there a better solution that you know?
     
  2. unity_BA3036A5CF9EA7D4F796

    unity_BA3036A5CF9EA7D4F796

    Joined:
    Dec 16, 2022
    Posts:
    4
    The top variant also seems more intuitive to me. Would also like to know which is best.
     
  3. cerestorm

    cerestorm

    Joined:
    Apr 16, 2020
    Posts:
    639
    They're both doing essentially the same thing, using NetworkObjectReference black boxes this lookup which, in the unlikely event that the storing of spawned objects changes means it would still work where the first rpc would fail. Both rpc's send only the id from the client to the server.

    Incidentally it's possible by the time the rpc is called on the server that object has been despawned so use TryGetValue or TryGet to retrieve it.
     
  4. IStealKneeCaps

    IStealKneeCaps

    Joined:
    Oct 8, 2017
    Posts:
    2
    Oh okay I didnt know that, I was thinking that sending an entire struct over the network would create a larger amount of lag due to more data needed to be downloaded, but if they both only send ID then that makes my concern invalid. Thank you :D