Madmitten
Madmitten

Reputation: 135

Unity editor freezes when running a certain function

I created a function that will run until an images fillamount is at 0. However when I call this function from another class the unity editor completing freezes. I cant even stop pause play mode.

The class that calls the cooldown function.

Cooldown cooldown;
    
cooldown = gameObject.GetComponentInChildren<Cooldown>();//Sets cooldown to have the same values as the prefab.
    
    public void gatherCooldown()
    {
        cooldown.resourceCooldown();
    }

Cooldown Class

public class Cooldown : MonoBehaviour
{
    public Image imageCooldown;
    public float cooldown = 5;
    public bool isCooldown

    public void resourceCooldown()
    {
        while (imageCooldown.fillAmount >= 0)
        {
            imageCooldown.fillAmount -= 1 / cooldown * Time.deltaTime;
        }

    }
}

Upvotes: 1

Views: 898

Answers (2)

IndieGameDev
IndieGameDev

Reputation: 2974

You are currently using a blocking method. To fix that you could use a Corountine instead to decreasing your images fillAmount.

Coroutine Example:

private IEnumerator DecreaseFillAmount() {
    // Entered the Coroutine
    isCooldown = true;
    // Repeat until the fillAmount is smaller than or equal to 0
    while (imageCooldown.fillAmount > 0) {
        imageCooldown.fillAmount -= (1 / cooldown) * Time.deltaTime;
        yield return null;
    }
    // Left the Coroutine
    isCooldown = false;
}

You also need to make sure that you call your Coroutin the right way, you achieve this with StartCoroutine().

Calling the Coroutine:

public void resourceCooldown() {
    // Call the DecreaseFillAmount Coroutine.
    StartCoroutine(DecreaseFillAmount());
}

Upvotes: 2

derHugo
derHugo

Reputation: 90580

Your while is freezing the main thread.

This should probably rather be a Coroutine

public class Cooldown : MonoBehaviour
{
    public Image imageCooldown;
    public float cooldown = 5;
    public bool isCooldown;

    private IEnumerator CooldownRoutine()
    {
        isCooldown = true;

        while (imageCooldown.fillAmount >= 0)
        {
            imageCooldown.fillAmount -= 1 / cooldown * Time.deltaTime;

            // Tells Unity to "pause" this routine, render this frame
            // And continue from here in the next frame
            yield return null;
        }

        isCooldown = false;
    }

    public void resourceCooldown()
    {
        StartCoroutin(CooldownRoutine ());
    }
}

Upvotes: 1

Related Questions