Home > database >  Score update. Change in every 5 seconds
Score update. Change in every 5 seconds

Time:05-19

I'm new to unity and I'm developing a 2d game. I want my game to update the "scoretext" every 5 seconds and I want it to update for 1. But my code is not working. It is updating in like 0.000...1 second (I mean the program doesn't wait 5 seconds to update). How can I fix this? Thanks!

public Text scoretext;
public int score;



IEnumerator scoreup()
    {
        score  ;
        scoretext.text = score.ToString();
        yield return new WaitForSeconds(5);
    }

void Update()
    {
        StartCoroutine("scoreup");
    }

CodePudding user response:

Solution 1:

Simple use of InvokeRepeating code:

void ScoreUp()
{
    score  ;
    scoretext.text = score.ToString();
}
void Start()
{
    InvokeRepeating(nameof(ScoreUp), 0f, 5f); // 0=delay, 5f = repeat Time
}

Solution 2:

Use an IEnumerator:

IEnumerator ScoreUp(int amount = 1)
{
    while (true)
    {
        score  = amount;
        scoretext.text = score.ToString();
        yield return new WaitForSeconds(5);
    }

}
private void Start()
{
    StartCoroutine(ScoreUp(2));
}
  • Related