Specific explanations of coroutine in Unity3d

Source: Internet
Author: User

This article is too messy, recommended Frankjfwang: Comprehensive analysis of Coroutine technology

The Coroutine in unity is achieved through yield expression; This code is seen everywhere in the official script.

Questions:

What is yield?

What is Coroutine?

What's so weird about Unity's coroutine program running process?

What is the principle of coroutine in unity and how is it implemented?

What issues do you need to be aware of when using unity Coroutine?


one, yield in several languages of the program running characteristics :

The yield in Lua is to suspend the cooperative function execution and pass the parameters to resume. The resume makes the cooperative function suspend-and-execute and passes the parameters to the synergistic function.

The yield return/break in C # is used to return the values (like iterations) inside the function query collection generator and record the current scene, and continue running down the next query from the yield field of the last record until it continues to run. Then exit the logic of this yield.

Yield break terminates the yield iteration logic and jumps out.
Yieldimplementation:
1). Caller callsfunction
2). Caller Requestsitem Request an element on demand
3). Next itemreturned returns the requested element
4). Goto Step #2

The yield expression in Python, which has a yield function, becomes a generator, calling the function to return an iterator object, invoking the next method with an iterator object (or invoking the next method on its own initiative). The function is started and is interrupted when it runs to yield expression. Returns the current value of the iterator. And keep the scene, the next call to next will start from the scene to run, the iteration stopped. You can see that yield in Python is similar to yield in C #, used to create generators, run-time interrupts to return iterator values, and record the scene to continue running the next time from the field.

The yield in unity is similar to that in C#,python. Because unity is based on the. NET Framework, and the unity script starts with Boo (a variant of Python).

Only the Coroutine feature type is more in unity. And Startcoroutine's Coroutine management class. Startcoroutine is not starting a new thread. Instead, a synergistic program is started, and the default unity all code is in one line approached (http://answers.unity3d.com/questions/280597/new-thread-vs-startcoroutine.html).

The principle of Coroutine language level:

Two years ago, the process seemed to be a very advanced thing, and then most languages supported the process more or less. I'm more familiar with the goroutine of Python's Gevent,lua coroutine,go. In particular, LUA and go, the language itself supports the co-process. The co-process is also called lightweight threading.

The popular point is to define a lot of tasks. And then, through a thread, it executes for each task and executes it cooperatively. What 's great about it is that every time you perform a task. It can be executed from the point where the task was last interrupted .

In our general impression, only the operating system to the thread scheduling when it will do this kind of thing, do a variety of stack, save state.

And the co-process, in total, is only executed in one thread. If you use the system stack of the thread itself, it's already a storm. So here, the implementation of the time is to use memory to simulate the operation of the stack . Detailed implementation, I think the complexity must be very small.

We know that threads are lighter than processes, so a thread consumes less resources than processes, and context switching is more economical than process. The co-turndown thread is more lightweight. Context switching is more rapid.

So in the server programming to give people infinite imagination. Although there is no mainstream webserver to use the process. But the performance of the Web services developed by the go language has come to the fore.


second, Unity's coroutine operation phenomenon :

The first method:

Voidstart ()

{

Print ("starting" +time.time);----------------------------------------1

Startcoroutine (Waitandprint (2));-------------------------------------2

Print ("Done" +time.time);-------------------------------------------3

}

IEnumerator Waitandprint (float waitTime)

{

Yield return new waitforseconds (waitTime);------------------------4

Print ("Waitandprint" + time.time);----------------------------------5

}

This code is run in 12435 order.

Run to 4 to register the event, control over to the external thread. The external thread runs to 3. event occurs, the program segments the mechanism of running Goto to the path where the stack information is logged to run the 5 statement.


IEnumerator Start ()

{

Print ("starting" +time.time);----------------------------------------1

Yield return Startcoroutine (Waitandprint (2.0F));------------------------2

Print ("Done" +time.time);------------------------------------------3

}

IEnumerator Waitandprint (float waitTime)

{

Yield return new waitforseconds (waitTime);----------------------------4

Print ("Waitandprint" + time.time);-----------------------------------------5

}

This code is run in 12453 order.

Why? It's such a strange way to run.

The program runs to 4. Run yield return expression register event handing over control to the outside, because the outside also need to hand over control also need to run the expression statement after yield return so it will re-enter the Waitandprint function then the current state of the next step to run, so run to 5,yield Return after the expression statement runs complete control is fully surrendered before running 3, the root cause is that yield return cannot be directly nested behind the need to follow an expression (event).



Third,the unity Official document to Coroutine explanation :

Normal coroutine Updates is run after Theupdate function returns . Acoroutine is a function of can suspend its execution (yield) until the givenyieldinstruction finishes. Different uses of coroutines:

yield ; The coroutine would continue after all Update functionshave been calledon thenext frame.

yield Waitforseconds (2) ; Continueaftera specified time delay, the After all Update functions has been called for Theframe.

yield waitforfixedupdate () ; Continueafter allfixedupdate have been called on all scripts.

yield WWW . Continue After a WWW download has completed

yield Startcoroutine (MyFunc); Chains the Coroutine, and would wait for the MyFunc coroutine to Completefirst .

C # is to add Returnkeyword between yield coroutine.


Iv. The Coroutine principle in unity pushes :

virtual machine staging mechanism. The same type of embedded stack holds for serial operation :. NET virtual machines in each frame loop, each of the compiler's pre-defined portals is entered in turn. For the coroutine type, the compiler needs to generate some code . after the time or event that is specified by the Coroutine type (. NET virtual machines are labeled with function pointers to manage the field and to send messages after each frame check time in the process or when an event is met, Give the full power of the CPU to the scene where yield is interrupted . or by managing each coroutine with multiple management classes that include different Coroutine iterators, each frame is reached by a polymorphic check time or event with Coroutine subclasses. The full power of the CPU is given to the Coroutine sub-class interrupt field ). continue down from the code where the yield was interrupted, thus creating a mechanism that we see as a function that can be segmented.

For nested coroutine types, it runs serially instead of parallel, possibly. NET virtual machine for the same coroutine type with the stack storage, the top of the stack run first, so that the serial operation , Assuming that the outer layer does not use yield return, it does not run serially, but runs in parallel.

You can then explain the sequence of operations in the example above.

Schematic diagram:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvqmx1zxmxmdix/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

See: http://www.richardfine.co.uk/2012/10/unity3d-monobehaviour-lifecycle/

In fact, yield waitforseconds/null/waitforendofframe is driven by the entire game while loop, Yield simply surrenders control to the external main thread and Coroutine sets the event to suspend Coroutine (not the thread is just a staging mechanism). When an event occurs (no next frame arrives.) However, in a fixed time period before or after the update or after the render, more than the next frame will go to the code inside the process.

V. Issues to be aware of when using coroutine in unity:

1. Place of use and place of inability to use:

Yield coroutine must be called in Monobehaviour or classes that inherit from Monobehaviour.

Yield cannot be used in update or fixedupdate.

2. Open the co-process:

Startcoroutine (String methodName) and Startcoroutine (Ienumeratorroutine) are capable of opening a co-process.

Difference:

When you use a string as a parameter, you can only pass one parameter at a time when the process is turned on, and the performance consumption will be greater. There is no limit to the use of IEnumerator as a reference.

3. Delete the process:

1). In Unity3d, use Stopcoroutine (stringmethodname) to terminate the Monobehaviour a cooperative program that specifies the method name, using the Stopallcoroutines () To terminate all the cooperative programs that the Monobehaviour can terminate.

Containing Startcoroutine (IEnumerator routine).

2). Another way to terminate the collaboration program is to set the active property of the Gameobject in the co-program to False, and when the active is set to Ture again, the co-program does not open again.

This does not take effect if you set the enabled script for the collaboration program to false.

Differences in use in 4.js and C #:

Yield return instead of yield is used in C #.

The yield (break) statement in C # must be in the IEnumerator type, and the return type of the C # method is IEnumerator. Return values such as (Eg:yield return new Waitforseconds (2); or yield returnnull);

5. The association function returns the value and the parameter type. Combined design pattern:

The return type of the synergistic program is the Coroutine type. In Unity3d, the Coroutine class inherits from Yieldinstruction, so the return type of the co-program can only be null, the number of frames waiting (frame), and the waiting time.

The number of references in the co-program cannot specify ref, out parameters. However, when we use the WWW class, we often use a synergistic program. You cannot output an object because the parameter address (reference) cannot be passed in the co-program.

This makes it possible to rewrite a co-program for each WWW object that is downloaded. The solution to this problem is to create a WWW-based class (which is solved by a combination of patterns -in fact, not by a function that passes through the Global Association of Objects ), and implements a download method. For example, the following:

Using Unityengine;

Using System.Collections;

public class Wwwobject:monobehaviour

{

public www www;

Public wwwobject (string url)

{

if (Gamevar.wwwcache)

www = WWW.LoadFromCacheOrDownload (URL, gamevar.version);

Else

www = new www (URL);

}

Public IEnumerator Load ()

{

Debug.Log ("Start loading:" + Www.url);

while (!www.isdone)

{

if (gamevar.gamestate = = Gamestate.jumping | | Gamevar.gamestate ==gamestate.jumpingasync)

loadscene.progress = www.progress;

Yield return 1;

}

if (www.error! = null)

Debug.logerror ("Loading error:" + Www.url + "\ n" +www.error);

Else

Debug.Log ("End loading:" + Www.url);

}

Public IEnumerator Loadwithtip (string resourcesname)

{

Debug.Log ("Start loading:" + Www.url);

LOADSCENE.TIPSTR = "Downloading resources<" + resourcesname + "> ...";

while (!www.isdone)

{

if (gamevar.gamestate = = Gamestate.jumping | | Gamevar.gamestate ==gamestate.jumpingasync)

Loadscene.progress= www.progress;

Yield return 1;

}

if (www.error! = null)

Debug.logerror ("Loading error:" + Www.url + "\ n" +www.error);

Else

Debug.Log ("End loading:" + Www.url);

}

}

Call:

Using Unityengine;

Using System.Collections;

Using System.Collections.Generic;

public class Loadresources:monobehaviour

{

static string url = "Http://61.149.211.88/Package/test.unity3d";

public static www www = null;

IEnumerator Start ()

{

if (! gamevar.resourcesloaded)

{

Gamevar.gamestate = gamestate.jumping;

Wwwobject obj = new Wwwobject (URL);

www = obj.www;

Yield return startcoroutine (obj. Loadwithtip ("textures"));

Gamevar.resourcesloaded = true;

Gamevar.gamestate = Gamestate.run;

}

}

}

Articles:

http://game.ceeger.com/forum/read.php?tid=13148

http://www.zhihu.com/question/23895384

http://blog.csdn.net/tkokof1/article/details/11842673

http://blog.csdn.net/tkokof1/article/details/12834939

http://www.richardfine.co.uk/2012/10/unity3d-monobehaviour-lifecycle/

http://dsqiu.iteye.com/blog/2029701

Specific explanations of coroutine in Unity3d

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.