I’m working on an options menu, and one of its options is to enable performance statistics. One of them being the player’s current ping.
I’ve isolated just the relevant code and wonder if it’s actually good/accurate.
LocalScript:
--// Services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
--// Folders
local remotesFolder = ReplicatedStorage.Remotes
--// UI
local performanceFrame = script.Parent
local pingText = performanceFrame.Ping
--// Ping variables
local pingConnection
local pingSamples = {}
local lastPingSent = 0
local pingSendRate = 0.25
--// Ping
local function TogglePing(toggle: boolean)
if toggle then
if pingConnection then return end
pingConnection = RunService.RenderStepped:Connect(function()
local now = tick()
if now - lastPingSent >= pingSendRate then
lastPingSent = now
local serverTime = Workspace:GetServerTimeNow()
remotesFolder.PingEvent:FireServer(serverTime)
end
end)
else
if pingConnection then
pingConnection:Disconnect()
pingConnection = nil
end
lastPingSent = 0
table.clear(pingSamples)
pingText.Text = "Ping: 0 ms"
end
end
--// Ping smoothing for textlabel
local function AddPingSample(ping: number)
table.insert(pingSamples, ping)
if #pingSamples > 10 then
table.remove(pingSamples, 1)
end
end
--// Get average ping from samples
local function GetAveragePing(): number
local total = 0
for _, value in ipairs(pingSamples) do
total += value
end
return total / math.max(#pingSamples, 1)
end
--// Response from server
remotesFolder.PingEvent.OnClientEvent:Connect(function(clientSendTime: number)
local now = Workspace:GetServerTimeNow()
local ping = (now - clientSendTime) * 1000
AddPingSample(ping)
pingText.Text = string.format("Ping: %.0f ms", GetAveragePing())
end)
--// Toggle performance stats (there are more, but for relevance sake, it's just the TogglePing)
performanceFrame:GetPropertyChangedSignal("Visible"):Connect(function()
local toggle = performanceFrame.Visible
TogglePing(toggle)
end)
Server script:
--// Services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
--// Folders
local remotesFolder = ReplicatedStorage.Remotes
--// Update player ping
remotesFolder.PingEvent.OnServerEvent:Connect(function(player: Player, clientSendTime: number)
remotesFolder.PingEvent:FireClient(player, clientSendTime)
end)