Search Unity

Question Network ping calculation

Discussion in 'Netcode for GameObjects' started by andreyshade, May 10, 2022.

  1. andreyshade

    andreyshade

    Joined:
    Aug 8, 2017
    Posts:
    10
    What is the right way to calculate ping between client and server?
     
  2. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    There does not seem to be a built-in way to do it. The way I do it myself is to have a coroutine running on each player object that every 0.1 seconds notes the time, calls a ServerRpc that immediately calls a ClientRpc on the same client, where the time is again noted and the difference stored (the round-trip time, RTT). The ping is then half the average of the last N RTT measures, where I've set N=30 (so ~3 seconds). At the same time, the server runs a coroutine that does the opposite (call a ClientRpc that calls a ServerRpc) so the server knows the ping to every client.
     
  3. tkejran

    tkejran

    Joined:
    Sep 1, 2017
    Posts:
    1
    Afaik netcode already syncs local time to server, so
    LocalTime - ServerTime
    should give you proper ping value, no?
     
  4. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    That also works, yes – although this seems to be averaged over a longer length of time, and adds a tick from what I've seen, so depending on your application you'd subtract 1/(tick rate) (so for a tick rate of 50, you'd subtract 0.02 seconds).
     
  5. luke-unity

    luke-unity

    Joined:
    Sep 30, 2020
    Posts:
    306
    LocalTime - ServerTime 
    will give you a more accurate value for how the ping will "feel" like for a player when they move via NetworkTransform, so if you want to display a number to the player I'd recommend to use that one.
     
    andreyshade likes this.
  6. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    Isn't that only true for interpolated movement?
     
  7. Music_Corner

    Music_Corner

    Joined:
    Mar 8, 2020
    Posts:
    23
    Should i use (LocalTime - ServerTime).Tick or (LocalTime - ServerTime).Time to get milliseconds of a ping?

    UPD: I used (LocalTime - ServerTime).Tick and it feels like a proper thing to go with
     
    Last edited: Mar 5, 2024