counting down a variable issue
hi complete noob here lets get to it, my player collects coins. At the end of the level it displays how many coins were collected. The number of coins will be added to the total score. An animation of the numbers decreasing in the text ui box is what i want, ive achieved this from this question here however for some reason it shows the amount of coins that were collected just fine and then counts down to -114 is there something im missing?
here is my script updating the text
[SerializeField]
Text coinText;
[SerializeField]
globals coinScript;
[SerializeField]
public float speed;
public int countdown;
void Awake()
{
countdown = globals.allCoinsCollected;
if (coinText != null && coinScript != null)
{
coinText.text = countdown.ToString();
}
}
IEnumerator MyCoroutine()
{
while (countdown >= 1)
{
yield return new WaitForSeconds(1.0f);
countdown--;
}
}
void Update()
{
StartCoroutine("MyCoroutine");
coinText.text = countdown.ToString();
}
}
and the text and global script are set in the editor, as earlier mentioned. It displays the correct amount of coins collected but then counts down to -114
Answer by jgodfrey · Feb 21, 2016 at 12:35 AM
That bare call to "StartCoroutine" in Update is likely problematic. I assume you don't want to start the coroutine on every frame, right? Depending on your needs, you probably want to start the coroutine from Awake/Start. If you need to start it from Update for some reason, you probably only want to start it once. Certainly, not every frame...
that was exactly it thank you very much! must have been sleep drunk or something
Answer by codeman_nz · Feb 21, 2016 at 10:10 AM
Move you Update code to Start and that should solve your issue.
Yeah solved it i was working too late i think lol thank you :-)
Your answer
Follow this Question
Related Questions
Unity crashes when using while loop 0 Answers
Countdown timer for starting game 0 Answers
Switch Case help 0 Answers