Changing a value on a coroutine without having to write the coroutine multiple times

EXAMPLE
this script turns a text off and on a couple times

    public IEnumerator TextFlash()
    {
        Weapon1text.enabled = false;
        yield return new WaitForSeconds (textFlashSpeed);
        Weapon1text.enabled = true;
        yield return new WaitForSeconds (textFlashSpeed);
        Weapon1text.enabled = false;
        yield return new WaitForSeconds (textFlashSpeed);
        Weapon1text.enabled = true;
    }

on another script, we call the TextFlash function if we grabbed weapon 1, but what i want to do is, what if kept adding weapons, i would have to do TextFlash2, 3, 4 etc…? doesn’t seem clean so

is there a way to do this:

on the other script when we call TextFlash, we say which Text we want to flash ?

Sure, pass the Text object as a parameter to the coroutine? :slight_smile:

3 Likes

Abstract it into it’s own method… something like:

public static IEnumerator TextFlash(Text txt, int count, float speed)
{
    var wait = new WaitForSeconds(speed);
    for(int i = 0; i < cnt; i++)
    {
        txt.enabled = false;
        yield return wait;
        txt.enabled = true;
        yield return wait;
    }
}

Stick that wherever you want to make it easily accessible. And then call it from your script like so:

StartCoroutine(TextFlash(Weapon1text, 2, textFlashSpeed));
4 Likes

You can pass arguments to the method just as usual. Just add a Text argument to the method and modify it instead off a public variable. Then just pass the Text you want to flash when starting the coroutine.

Thanks!!! very helpful

also just curious why you put method as static ?

Static is useful for helper methods that can be called from anywhere in the project. Its reasobably safe, as long as the static method has no state of its own, and only acts on the state that was passed in.

1 Like