Code (CSharp): Ping ping; List<int> pingList; void Start () { pingList = new List<int> (); ping = new Ping ("216.52.241.254"); StartCoroutine (PingUpdate()); } IEnumerator PingUpdate() { yield return new WaitForSeconds (1f); if (ping.isDone) { pingList.Add(ping.time); Debug.Log (ping.time); ping = new Ping ("216.52.241.254"); } StartCoroutine (PingUpdate ()); } I am still new to unity, corountine and the ping class so i am not sure if i am doing it right. The code is supposed to collect pings once every sec(or more) and add it to a list. is there any hidden bugs in my code or like is there a better way of doing what i am trying to do.
From what i just read, you should use Ping.Ping(ip) instead of new Ping(ip), so Code (CSharp): Ping ping; List<int> pingList; void Start () { pingList = new List<int> (); ping = Ping.Ping("216.52.241.254"); StartCoroutine (PingUpdate()); } IEnumerator PingUpdate() { yield return new WaitForSeconds (1f); if (ping.isDone) { pingList.Add(ping.time); Debug.Log (ping.time); ping = Ping.Ping("216.52.241.254"); } StartCoroutine (PingUpdate ()); }
That is the constructor, you'd say '... new Ping(...'. The only thing I would say is wrong with your code is that you only wait a second for your ping to finish. There's no guarantee that ping is done in that time. You should yield null until the ping is complete... but if you ALSO want a 1 second delay between pings... do both. Furthermore, you can just loop in PingUpdate instead of starting a new coroutine. Something like this: Code (csharp): using UnityEngine; using System.Collections.Generic; public class PingExample : MonoBehaviour { private List<int> _pingTime = new List<int>(); void Start() { this.StartCoroutine(PingUpdate()); } System.Collections.IEnumerator PingUpdate() { RestartLoop: var ping = new Ping("216.52.241.254"); yield return new WaitForSeconds(1f); while (!ping.isDone) yield return null; Debug.Log(ping.time); _pingTime.Add(ping.time); goto RestartLoop; } } Personally I like using goto for my loop, you could also just say 'while(true)'.
Wow! goto! did I just fall through a time wormhole and travel 30 years back in time? Only kidding, it's just been a long time since I've seen it used. Just like to add that there's no reason not to here btw.