Unity C# CoRoutine Not Working

Hey all,

I am trying to run a function after a delay, but it isn’t any way to do it in C# other than CoRoutine. My code is:

    IEnumerator Upgrade() {
        return new WaitForSeconds(3);
        Lvl++;
    }

void Start() {
        Button.onClick.AddListener(StartCoroutine(Uprgade()));

}

In short, I am trying to increase Lvl on a button click, after a 3 second delay. What am I doing wrong?

Thank you.

Easy mistake to make. You want to reference a method but your code is actually executing it.

void DoUpgrade()
{
    StartCoroutine(Upgrade());
}

button.onClick.AddListener(DoUpgrade); // note no parenthesis
2 Likes

I believe StartCoroutine(Uprgade()) will start your coroutine immediately on Start() and only run once.

Try putting this command inside a separate UnityAction method and add that as a listener.

I did that, but it gives me the Cannot implicitly convert type UnityEngine.WaitForSeconds' to System.Collections.IEnumerator’

What do I do?

That is pseudo-code. Examine the code, apply the concept to your script.

The problem is just as he said, you’re actually running the method when you’re adding the listening, so just make a new method that does nothing more than StartCoroutine() and add the subscriber to that method instead of the coroutine directly.

If you get errors, debug them as usual. (such as using yield return commands properly)