T
T
there42018-05-23 11:45:35
Unity
there4, 2018-05-23 11:45:35

How to correctly request a method from Update?

Hey! There is a countdown script in update. Every 30 seconds I need to output the TimerStatus. But my method is displayed several times until the timer is 30. Help win this!

function Update()
{
  if (!isTimerEnd) {
    timer -= Time.deltaTime; 
  } 

  if (timer > 0) {
    var mDisplay : String = parseInt( timer / 60 ).ToString();

    var sDisplay : String = parseInt( timer ).ToString();
     
    if ( (timer - ( parseInt(mDisplay) * 60)) > 10 ) {
         sDisplay = parseInt( timer - ( parseInt(hDisplay) * 60) ).ToString();
    } 
    else {
      mDisplay = "0" + parseInt( timer - 
                          ( parseInt(hDisplay) * 60) ).ToString(); 
    }

    if (sDisplay == "30" && !calledTimerStatus ) {
       calledTimerStatus = true;
       TimerStatus();
    } else calledTimerStatus = false;  
    
  }
}
function TimerStatus() {
  Debug.Log("30 sec stat");
}

Result:
5b05446c6d24a185076151.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2018-05-23
@there4

First, do not use UnityScript, it is no longer supported, and in 2018.2 it will be completely cut out.
Second, parsing a number into an int, turning it into a string, and comparing it to the string representation of the number is a bad idea. Are you saving variables or what?
Thirdly, don't use Invoke, calling methods on a string is a very bad practice, not to mention that in your case it is not needed, a direct call is enough.
As for the repeated call to TimerStatus, everything is simple here. Update is called many times per second, and the sDisplay value changes once per second, the simplest solution is to add a checkbox that will be set every thirty seconds and reset the rest of the seconds.

if (seconds == 30)
{
    if (!calledTimerStatus)
    {
        calledTimerStatus = true;
        TimerStatus();
    }
}
else
{
    calledTimerStatus = false;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question