- Home /
Compare two time strings?
So I have a timer code that counts up when starting a game. Then I convert the output of the timer to a highscore variable(string) after the game is finished. So if I start a new game, I want to check whether the new output of the timer is greater or lower than the highscore variable? Any suggestions?
Timer code:
     public Text counterText;
 
     public float seconds, minutes, startTime;
 
     // Initialization
     void Start()
     {
         counterText = GetComponent<Text>() as Text;
         startTime = Time.time;
     }
 
     // Update once per frame
     void Update()
     {
         minutes = (Time.time - startTime) / 60f;
         seconds = (Time.time - startTime) %  60f;
         counterText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
     }
and the timer stops when it reaches the finish line(trigger)
     public GameObject successfulCanvas;
     public Text score;
     string finalScore = "None";
 
     private void OnTriggerEnter2D(Collider2D collision)
     {
         if (collision.CompareTag("Player"))
         {
             Time.timeScale = 0;
             successfulCanvas.SetActive(true);
 
             if(score.text >= finalScore) //help here
 
             finalScore = score.text; //ignore
         }
     }
Answer by Hellium · Jan 15, 2019 at 10:00 AM
 public Text counterText;
 
  private float seconds, minutes, startTime;
  public float TimeElapsed
  {
       return Time.time - startTime;
  }
 
  // Initialization
  void Start()
  {
      counterText = GetComponent<Text>() as Text;
      startTime = Time.time;
  }
 
  // Update once per frame
  void Update()
  {
      minutes = TimeElapsed / 60f;
      seconds = TimeElapsed %  60f;
      counterText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
  }
  public GameObject successfulCanvas;
  // Drag & drop the gameObject holding the `Time` script
  // (supposing your 1st script is called Timer)
  public Timer Timer;
  float highScore;
 
  private void OnTriggerEnter2D(Collider2D collision)
  {
      if (collision.CompareTag("Player"))
      {
          Time.timeScale = 0;
          successfulCanvas.SetActive(true);
 
          if(Timer.TimeElapsed >= highScore)
               highScore = Timer.TimeElapsed;
      }
  }
I cannot use a method to conduct mathematical operations with float. TimeElapsed is causing this.
I don't really understand what exact problem you are facing. I couldn't you use float comparison?
Answer by xxmariofer · Jan 15, 2019 at 10:00 AM
The easiest solution is to use int.Parse (or Tryparse.) to convert you score string to int again
int _score = int.Parse(score.text);
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                