Unity how do coroutines work




















After changing in the line of yield, save it and push play button in Unity. Here WaitForSeconds waits for specified amount of time in our case it is 0. For better understanding, play around with different values to see the effect of WaitForSeconds. WaitForSeconds is a very useful in sequencing animations and stuff. How will you handle execution when nothing is to be performed? As Update will be called even though nothing is to be done.

Alternatively we can use some boolean like "isPlaying"? But the main problem is it's sloppy, since Update will needlessly keep checking this long after the desired effect is over. This would be something like calling out someone continuously knowing that no one is supposed to respond! By using Coroutine your code gets shorter and it does help in optimization of code. Coroutines have only a tiny overhead and can be preferred over an Update method that is called all the time needlessly.

Typically there are three situations where it makes a lot of sense to use coroutines that I can think off the top of my head. When you want to sequence things like animations and state machines. Here, first animation state is changed, then the camera state is changed , and it waits till the movement of player is over.

As soon as the player movement is over the state is changed back to the idle and respective motion method is called. Now if you check the third line, another coroutine is called player. The foreach loop in Main does not need to be touched — we still want to iterate over the result of this method. Except, running this code, you will immediately see the difference this made.

Correct it does! Lists, arrays, queues, stacks, dictionaries, anything which can be enumerated implements IEnumerable. IEnumerator , on the other hand, is a type which is responsible for defining how these enumerables should be enumerated. In short, IEnumer able is a collection of values. IEnumer ator is responsible for iterating over such collections. You may have noticed that types such as arrays and lists all define a GetEnumerator method.

This method returns a type which implements IEnumerator responsbile for implementing the way that the current collection must be enumerated. Save for arrays, because those compile slightly differently, a foreach actually compiles to a while loop which runs for as long as IEnumerator.

MoveNext returns true. You can see this in action here! We can browse the. We see that the enumerator tracks the current index, as well as the value at that index. But every call to MoveNext checks if the index is within the bounds of the list.

So the while loop we saw above is simply asking the enumerator to move to the next index, and then accesses Current. This is the reason a foreach calls GetEnumerator — because different collection types need to be enumerated differently. You will notice that the loop counter in the Fade function maintains its correct value over the lifetime of the coroutine. In fact any variable or parameter will be correctly preserved between yields. By default, a coroutine is resumed on the frame after it yields but it is also possible to introduce a time delay using WaitForSeconds :.

This can be used as a way to spread an effect over a period of time, but it is also a useful optimization. Many tasks in a game need to be carried out periodically and the most obvious way to do this is to include them in the Update function. However, this function will typically be called many times per second.

An example of this might be an alarm that warns the player if an enemy is nearby. The code might look something like this:. Therefore, our coroutines must return an IEnumerable or IEnumerator object. Furthermore, the class generated does more than enable iteration over data. The class is also a state machine that tracks the state of the iteration block. It stores the current state of the function, including all variables used within the method and where the code is up to in terms of executing.

The above coroutine translates a GameObject by units in x-axis and the after waiting five seconds translates that GameObject back to its original position. The function executes in the following order:. Yield can return any expression, however in Unity they return a set of objects that all inherit from YieldInstruction.

A coroutine uses YieldInstruction objects to implement specific behaviour, like waiting until the end of the current frame or like we did in our example, waiting five seconds. For completeness, here is a simple example of how these objects might work.

We could have a base class YieldExpression that has a single method IsDone. All this class does is grab the current time when the object is first created. MonoBehaviour passes the IEnumerator object returned from a coroutine through StartCoroutine and StopCoroutine so each instance of MonoBehaviour is tasked with managing its own coroutines.

The above CoroutineManager class is part of the behaviour I believe would be inside of MonoBehaviour. It has methods for starting and stopping coroutines. StartCoroutine adds the IEnumerator and calls MoveNext which starts running the code within the method until the first yield statement.



0コメント

  • 1000 / 1000