Search Unity

Show Ping.time to text

Discussion in 'Multiplayer' started by chedybm, Jul 16, 2017.

  1. chedybm

    chedybm

    Joined:
    Apr 29, 2017
    Posts:
    2
    Hi.
    I'm trying to show the ping result in screen text as the title says.
    - I need it to refresh every 1 sec.
    - I need the to break the method and restart it if the button is clicked again.
    this is my code, and it's not working.
    anyone can help me please ? :(

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine.UI;
    4. using UnityEngine;
    5. using UnityEngine.Networking;
    6.  
    7.  
    8.  
    9. public class TestPing : MonoBehaviour {
    10.  
    11.     public Text txt;
    12.  
    13.  
    14.  
    15.     void Start(){
    16.         txt = GetComponent <Text> ();
    17.     }
    18.  
    19.     public void onClick(){
    20.         Invoke ("Pingtest", 1f);
    21.    
    22.     }
    23.  
    24.     IEnumerator Pingtest(){
    25.        
    26.         while (true) {
    27.             var Pingtest = new Ping ("104.160.141.3");
    28.  
    29.    
    30.             while (!Pingtest.isDone) {
    31.                 yield return null;
    32.             }
    33.  
    34.             yield return new WaitForSeconds (1);
    35.             txt.text = (Pingtest.time).ToString();
    36.  
    37.         }
    38.     }
    39. }
    40.  
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    You're executing your coroutine instead of starting it. Use:
    Code (CSharp):
    1. private Coroutine _pingTest;
    2.  
    3. ...
    4. if (_pingTest != null){
    5.      StopCoroutine(_pingTest);
    6. }
    7.  
    8. _pingTest = StartCoroutine(Pingtest());
    9.  
    10. ...
    Instead of

    Code (CSharp):
    1. Invoke("Pingtest", 1f);
     
  3. chedybm

    chedybm

    Joined:
    Apr 29, 2017
    Posts:
    2
    Thank you so much :D
    that worked so well