I have a game where I want to make the current Ping available to the user, so I make some requests and store them in a list, old requests are removed.
My code is similar to this one, I made some simplifications so you don’t get bored, the problem here is not about the code, but how it should work:
public class Metrics : MonoBehaviour
{
public int pingAverage = -1;
void Start()
{
StartCoroutine(Refreshing());
}
IEnumerator Refreshing()
{
// Remember 10 pings.
const int WINDOW_SIZE = 10;
int sum = 0;
LinkedList<int> pings = new LinkedList<int>();
while (true)
{
// Simplified. Low precision.
float start = Time.timeSinceLevelLoad;
yield return conn.Request();
float end = Time.timeSinceLevelLoad;
if (!conn.err)
{
int ping = (end - start) * 1000;
sum += ping;
pings.AddLast(ping);
if (pings.Count > WINDOW_SIZE)
{
int first = pings.First.Value;
pings.RemoveFirst();
sum -= first;
}
pingAverage = sum / pings.Count;
}
else
{
// What i do here?
}
yield return new WaitForSeconds(0.5f);
}
}
}
With this code, if there are errors, it may be that the average ping is 10 ms, but 10 minutes ago that no measurements were made. I remember that for example League of Legends set Ping at 500 ms when the game was disconnected.
*Note that error checking sounds like a packet loss to me.