Search Unity

Question Coroutine not working after first time it is called?

Discussion in 'Scripting' started by Amarodil, Mar 29, 2023.

  1. Amarodil

    Amarodil

    Joined:
    Jan 25, 2019
    Posts:
    16
    Hello,
    I have the following coroutine meant to make a picture go from 1 alpha to 0. It works on the first time that it is called, but every consecutive time it just stays 1.

    Here is the script:
    private IEnumerator RemoveScreenDarkening()
    {
    for (float i = _fadeTime; i >= 0; i -= Time.deltaTime)
    {
    Debug.Log("Darkener Remover Alpha: " + i/_fadeTime);
    // set color with i as alpha
    blackFadeCover.GetComponent<Image>().color = new Color(0, 0, 0, i / _fadeTime);
    yield return null;
    }
    }

    On the first time this is started it properly outputs into the log the alpha values from 1 to 0.

    The second time it is run it only runs through the for loop once and outputs an alpha of 0. What could be causing this? I already trying to stop the previous coroutine before calling the new one and it didnt change.

    Any help is much appreciated! Thank you!
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,434
    Use your code tags. It's a button RIGHT THERE ON THE FORMATTING BAR, the only one with actual text telling you what it's for.

    Are you starting this with
    StartCoroutine(RemoveScreenDarkening())
    ? If the object which calls StartCoroutine gets disabled or destroyed, the coroutine will stop.
     
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,993
    What you posted is not "your script" but just your coroutine. We don't know how you call it, where you call it and how you use it. Also you should use code tags when posting code.