Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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:
    199
    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:
    199
    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

    Unity Technologies

    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:
    199
    Isn't that only true for interpolated movement?