Home > other >  How can I get this timer for my progress bar?
How can I get this timer for my progress bar?

Time:05-21

I'm currently learning how to create progress bars but Ive run into a problem. Im not sure how I can reference the running timer in my CraftCopperBar script for my update. Or if i have the wrong idea please correct me.

public IEnumerator CraftCopperBar()
{
    while (copper >= copperBarValue)
    {
        button.SetActive(false);
        copper -= copperBarValue;
        yield return new WaitForSeconds(5f);
        copperBar  = 1 * multiplier;

        if (copper < copperBarValue)
        {
            button.SetActive(true);
            break;
        }
    }

public void Update()
progressBar.fillAmount = (float)(x / 5f);

CodePudding user response:

Upgrade to auto continuous timer in IEnumerator. This is a good way to solve your problem, In the following code, you no longer need the Update event for fill progress.

public IEnumerator CraftCopperBar(float waitTime)
{
    while (copper >= copperBarValue)
    {
        copper -= copperBarValue;
        button.SetActive(false);

        var timer = 0f;
        while (timer <= waitTime)
        {
            timer  = Time.deltaTime;

            progressBar.fillAmount = timer / waitTime;
            
            yield return new WaitForEndOfFrame();
        }
        copperBar  = 1 * multiplier;

        if (copper < copperBarValue)
        {
            button.SetActive(true);
            break;
        }
    }
}

Also put wait time in parentheses.

public void Start() => StartCoroutine(CraftCopperBar(5f));
  • Related