Ienumerator/ienumerable/yield Return/startcoroutine Detailed

Source: Internet
Author: User

Ienumerator/ienumerable

Public interface IEnumerable  {      IEnumerator GetEnumerator ();  }     Public interface IEnumerator  {      bool MoveNext ();      void Reset ();         Object current {get;}  }  

In the use of both, there are the following points to note

1, a collection to support the traversal of the Foreach method, the IEnumerable interface must be implemented (that is, the IEnumerator object must be returned in some way).
2. IEnumerator object specifically implements the iterator (via MoveNext (), Reset (), current).
3, from the two interfaces of the choice of words, you can also see the difference: IEnumerable is a declarative interface, declares that the class implementing the interface is "enumerable (enumerable)", but does not describe how to implement the enumerator (iterator) IEnumerator is an implementation-type interface, IEnumerator object is a iterator.
4, IEnumerable and IEnumerator through the IEnumerable GetEnumerator () method to establish the connection, the client can pass IEnumerable GetEnumerator () Get IEnumerator object, in this sense, will GetEnumerator () as IEnumerator object factory method also can not be.


Yield return

The yield (break) statement must be in the IEnumerator type in Unity C #.

C # method, the return type of the method is IEnumerator, return value such as (Eg:yield return new Waitforseconds (2); or yield return null;).
Yield cannot be used in update or fixedupdate.

Yield is like a traffic light, and before it satisfies the condition immediately behind it, the process hangs, handing execution to the parent function that invokes it, and can execute the code that yields the following when the condition is met.


Normal coroutine Updates is run after the Update function returns. A Coroutine is function so can suspend its execution (yield) until the given given yieldinstruction finishes. Different Uses of coroutines:

Yield Wait all Update functions called,the coroutine would continue on the next frame.
Yield Waitforseconds (2); Continue after a specified time delay, after all Update functions has been called for the frame
Yield waitforfixedupdate (); Continue after all fixedupdate have been called on all scripts
Yield WWW; Continue after a WWW download have completed.
Yield Startcoroutine (MyFunc); Chains the Coroutine, and would wait for the MyFunc coroutine to complete first.

The difference between yield return and return is that the statement after return will not return to the back of return to continue execution.


Startcoroutine

In Unity3d, you can use the Monobehaviour.startcoroutine method to open a synergistic program, which means that the method must be called in a monobehaviour or class that inherits from Monobehaviour.

In Unity3d, a thread can be opened using Startcoroutine (String methodName) and Startcoroutine (IEnumerator routine). The difference is that using a string as a parameter allows the thread to be opened and terminated before the thread ends, whereas using IEnumerator as a parameter can only wait for the end of the thread to terminate at any time (unless the Stopallcoroutines () method is used), and when the string is used as a parameter. Only one parameter can be passed at most when the thread is turned on, and the performance consumption is a bit larger, while using IEnumerator as a parameter does not have this limitation.

In Unity3d, a stopcoroutine (string methodName) is used to terminate a synergistic program using Stopallcoroutines () to terminate all the cooperating programs that can be terminated, but both methods can only terminate the Monobehaviour in the process of collaboration.

There is also a way to terminate the co-program, set the active property of the Gameobject where the program is located to False, and when you set the active to Ture again, the co-program will no longer open It will not take effect if you set the enabled script for the collaboration program to false. This is because the co-operation is turned on as a thread, and Monobehaviour is a thread, they become non-interfering modules, unless the code is called, they work on the same object, only if the object is not visible to terminate the two threads at the same time. However, in order to manage our extra open threads, Unity3d put the call of the cooperative program in Monobehaviour, so that we can easily invoke the cooperative program in the specified script when we are programming, instead of being unable to manage it. In particular, it is easy to make mistakes in multi-person development by simply judging the thread based on the method name, which ensures that the object, the script is managed methodically, and the duplicate name is prevented.


Example 1

public class Gamemanager:monobehaviour {     void Start ()     {        Debug.Log ("starting" + time.time);        Startcoroutine (Waitandprint (2));        Debug.Log ("Done" + time.time);    } IEnumerator Waitandprint (float waitTime)     {         yield return new waitforseconds (waitTime);         Debug.Log ("Waitandprint" + Time.time);}    }


Operation Result:



public class Gamemanager:monobehaviour {IEnumerator Start ()     {Debug.Log ("starting" + time.time);        Yield return Startcoroutine (Waitandprint (2.0F));D Ebug. Log ("Done" + time.time);    } IEnumerator Waitandprint (float waitTime)     {         yield return new Waitforseconds (waitTime);D ebug. Log ("Waitandprint" + Time.time);}    }

Operation Result:


Example Two

The scene is as follows, a ball a plane.



The Controller of the ball

Using unityengine;using System.collections;public class Spherecontroller:monobehaviour {private Vector3 Target;public float smoothing = 7f;public Vector3 target{get {return Target;} Set{target = value; Stopcoroutine ("movement"); Startcoroutine ("movement", target);D Ebug. Log ("move!");}} IEnumerator movement (Vector3 target) {while (Vector3.distance (transform.position, target) > 0.05f) { Transform.position = Vector3.lerp (transform.position, Target, smoothing * time.deltatime); yield return null;}}}

The following script is dragged onto the ground

Using unityengine;using System.collections;public class Clicksetposition:monobehaviour {public Spherecontroller spherecontroller;//update is called once per framevoid update () {if (Input.getmousebuttondown (0)) {Ray Ray = CAMERA.MAIN.S Creenpointtoray (input.mouseposition); Raycasthit hit; Physics.raycast (Ray, out hit); if (hit.collider.gameObject = = Gameobject) {Debug.Log ("clicked!"); Vector3 newtarget = hit.point + new Vector3 (0, 0.5f, 0); spherecontroller.target = Newtarget;}}}

Run results



Reference

The Unity Process (coroutine) principle in-depth analysis and continuation-http://dsqiu.iteye.com/blog/2049743

Understanding of Synergy-http://www.cnblogs.com/shawnzxx/archive/2013/01/01/2841451.html

Yield (C # Reference)-https://msdn.microsoft.com/zh-cn/library/9k7k7cf0.aspx

Coroutines Unity Tutorial-http://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines

Ienumerator/ienumerable/yield Return/startcoroutine Detailed

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.