Flashing image using Coroutine, 2 problems

Hey guys. I want to make the alpha of an image blink two times within two seconds. I used a coroutine but stumbled upon some problems. First off, the code:

IEnumerator DepleteEnergy()
    {
        float endTime = 2f;
        float executionTime = 0f;

        while (executionTime < endTime)
        {
            if (GlobalMasterScript.GameState == GlobalMaster.GameStates.RaceInProgress)
            {
                executionTime += Time.deltaTime;

                Color c = HealthFGImage.color;
                c.a = Mathf.PingPong(executionTime * 2f, 1f);
                HealthFGImage.color = c;
            }

            yield return null;
        }
    }

Now my problems:
1] The alpha value is set to 1 by default. Unfortunately, when the coroutine starts, it will immediately jump to 0 and climb up from there. It will eventually end with alpha at 0. I basically need to invert the PingPong value so it starts and ends with 1. How would I do that?
2] I need to pause the coroutine when the game is paused. When pausing the game, Time.timeScale is set to 0. You can see I tried to implement something in my coroutine to make the coroutine pause aswell but it is not working. How can I pause the coroutine and continue it properly when GameState changes/Time.timeScale is 1?

Thanks in advance :slight_smile:

For #1, have you considered the following?

Mathf.PingPong(1f + executionTime * 2f, 1f)

For #2, have you tried the following?

Time.deltaTime * Time.timeScale

Also, you are animating the alpha value, why aren’t you just using animation?

Hey Max,

thanks for your reply.
#1 works like charm. Thanks alot for that! :slight_smile:
#2 didn’t do the trick. It looks like the routine would pause properly, cuz the alpha value is the same after resuming from pause but then it would not continue to run to finish.

To be honest, I haven’t done much with animations yet except moving objects. It is possibly the easiest way :slight_smile: However, I’d like to be able to achieve the same using code.

For the pause, a coroutine can suspend until another coroutine finishes. so something like:

if(gamestate.isrunning) yield return null:
else yield return startcoroutine(waitForPause);

I don’t know if the syntax is right, but that’s the idea.

OMG guys, I’m stupid.
After reading the Coroutine manual again, I noticed my mistake:
During pause, I disabled the whole GameObject that contained the Coroutine, so no wonder it did not continue. Now I leave the GameObject enabled and just disable it’s Canvas that holds the UI elements. And then my above code works :slight_smile:

Thanks again for your answers, you guided me to the solution :slight_smile: