RickyX
1
So i wrote a code that looks like this:
if (Something == true)
{
//did something
yield return new WaitForSeconds(1);
//did something
}
and i placed it under FixedUpdate, but it gives an error that says:
error CS1624: The body of `ScriptName.FixedUpdate()' cannot be an iterator block because `void' is not an iterator interface type
So why is this happening ? I never ever used yield before, i don’t even know what it is, i used invoke to a function instead, but i really want yield it’s faster, so why, what’s wrong.
As BM said, you don’t every want to yield within any Unity Lifecycle such as Start, Update, or Fixed Update.
This would result in your main thread hanging, probably crashing Unity if it had worked.
Instead, you want to run Yields in IEnumerators that are started via coroutine. There are exceptions to this, but as a beginner, this is how you should be using them. Here’s a standard example:
private void Start()
{
StartCoroutine(WaitForAFew());
}
IEnumerator WaitForAFew()
{
//Do Something Before the Wait
yield return new WaitForSeconds(3.0f);
//Do Something After the Wait
}
Kiwasi
2
You can’t yield inside of FixedUpdate. Call another function, and yield there.
You might want to know that:
InvokeRepeating("x", 1,1);
is generally slightly faster than:
StartCoroutine("x");
IEnumerator x() {
yield return new WaitForSeconds(1);
}
There’s plenty of other reasons to use coroutines, but “it’s faster [than] invoke” is not one of them, so if that’s your only reason for introducing yield, I’d stop now.
Try one of the following to learn more: