Anybody Remember Coroutines in Javascript (UnityScript)?

I’m trying to convert an old JavaScript project to C#, and I don’t remember how coroutines work in JS. Or at least how I coded them. I have many cases where I just called the coroutine (a function with a yield in it) like any other function, NOT preceded by a yield. For example:

DeletePiece();

function DeletePiece() {
// other stuff
yield;
}

In C#, this results in the function not being called. What I’m not sure about is, does calling a coroutine in JS without a “yield” pause execution of the calling function until the coroutine it finished, or does it continue without waiting?

Which of these would be the correct translation to C#?

StartCoroutine(DeletePiece);
or
yield return StartCoroutine(DeletePiece);

The other thing I’m confused about is, in the second case, if I add a “yield” when calling the coroutine, then that function becomes a coroutine (IEnumerator), which then needs to be called with a yield, then the function that calls that, and so on.

Coroutines essentially worked the same way in UnityScript as both C# and UnityScript are/were .NET languages. However in UnityScript many things were inferred automatically. So when calling a generator method (a method that returns an IEnumerator) UnityScript would have used StartCoroutine automatically.

Also just using yield; would be a yield return null; in C#

To to summarize. Your code, would be

IEnumerator DeletePiece()
{
    // other stuff
    yield return null;
}

And the calling line would be

// Starting coroutine DeletePiece();
StartCoroutine(DeletePiece());

Can’t remember all the quirks that UnityScript had as I barely used it. So your question is a bit too generic. If you have issues with a particular script, you should share that script.

In any case, you can read through my coroutine crash course (mirror on github) which explains what coroutine actually are and how they work behind the scenes if you’re interested.

1 Like