About Unity's coroutines

 coroutine

  1. Get to know coroutines

 // A coroutine is not multi-threaded: it is a piece of code that executes outside the main program

    //Coroutines are not affected by life cycle

    //Function: can directly execute the code at a specific time.

    //1, delay operation

    //2, wait for a certain code to execute after execution

    /*

     Features: 1. The coroutine is the same as the life cycle in the main thread, not asynchronous

           2. The code execution of the coroutine is determined according to the judgment conditions of the coroutine. When the conditions are not met, it suspends.

           Wake up after the condition is met and continue to execute

           3. The coroutine is the same as the life cycle. Every frame takes turns and executes after LateUpdate.

           4. In a coroutine in a script, when the script enable=false, the coroutine continues without being affected

           When the game object is not activated or destroyed,

 

         

      grammar:       

            The return value of the IEnumerator coroutine

           Judgment condition of yield return coroutine

        */

    IEnumerator testCoroutine() {

        print(1);

        yield return StartCoroutine("sunFunc");

        print(2);

    }

    IEnumerator Father()

    {

        print("Father");

        yield return StartCoroutine("Father");

        print("000");

    }

    object obj=new object();

    IEnumerator sun()

    {

        print("sun");

        

        yield return obj;

        print("222");

       

    }

    /*

       yield return return value (condition)

     1.yield return 0,1,2,3,,null

        print(2);

     Indicates that the following code waits for a frame to execute the code after yield return (such as Print(2))

     2. yield return new WaitForSeconds(2); execute after waiting for two seconds

     3. yield return StartCoroutine("sunFunc"); indicates that the newly opened sub-coroutine will be executed after the execution ends

     4. yield return new WaitForFixedUpdate(); execute after waiting for FixedUpdate

     5. yield return new WaitForEndOfFrame();等待GUI

     6. yield return new www; wait for www to execute and execute after execution

  

     Note : do not use coroutines in update, as normal methods can be executed without scripts

     Coroutines are executed immediately

    IEnumerator sun()

    {

        print("sun");

        

        yield return obj;

        print("222");

       

    }implement

    

     */

    void Start () {

        // StartCoroutine("testCoroutine"); start the coroutine with this

        // StartCoroutine(testCoroutine());

           StartCoroutine("sun");

        // StopCoroutine(); Close the specified coroutine. Execute to close the coroutine opened by the string

        // StopAllCoroutines(); all coroutines opened by the current script object

}

  1. yUse www to download image resources

    string url = "http://p0.so.qhimgs1.com/sdr/200_200_/t01b26e1155931cfd04.jpg";//The link of the picture

    string moveUrl ="http://www.unity3d.com/webplayers/Movie/sample.ogg";

    void Start () {

        StartCoroutine("downLoad");

}

    IEnumerator downLoad() {

        WWW www = new WWW (url);

        print(www.progress);//The progress of the download is displayed here

        print(www.isDone);//Whether the download is complete

        yield return www;//Wait for www to finish

 

        GetComponent<RawImage>().texture = www.texture;//Modify the texture of Raw

}

 

  1. Use www to download video resources

    string moveUrl = "http://www.unity3d.com/webplayers/Movie/sample.ogg";

RawImage rawImg;//RawImage's art can display video

    AudioSource aud;

    //video file

    MovieTexture mt;

    // Use this for initialization

    void Start () {

        rawImg = GetComponent<RawImage>();

        aud = GetComponent<AudioSource>();

        StartCoroutine("DownLoadMovie");

}

    //Used to observe the download progress progress

    IEnumerator DownLoadMovie() {

        WWW www = new WWW (moveUrl);

        while (!www.isDone) {//Determine whether to complete

            print(www.progress);//Output progress

            yield return null;

        }

        yield return www;

        //Start playing

        while (!www.GetMovieTexture().isReadyToPlay)

        {

            yield return null;

        }

        mt = www.GetMovieTexture();//Get the video texture obtained by www

        rawImg.texture = mt;//Set the texture of rawImg to the already or obtained video texture

        aud.clip = mt.audioClip;//Get the sound clip in the video

        mt.Play();//Video playback

        aud.Play();//Sound playback

}

  1. www loads local resources (images)

    Image img;

    IEnumerator LoadDown()

    {

        string path = "file://" + Application.dataPath + "/1 (2).jpg";//The address of the local resource starts with file:// This is the basic operation

        WWW www = new WWW (path);

        while(!www.isDone){

            print(www.isDone);

            yield return null;

        }

        Texture2D texture = www.texture;

        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));//Create a sprite using texture

        img.sprite = sprite;//Replace the sprite of the picture

    }

void Start () {

        img = GetComponent<Image>();

        StartCoroutine("");

}

  1. Download resources on the Internet, display a progress bar, and play when the video exists locally, download when it does not exist

using UnityEngine;//Reference class library

using UnityEngine.UI;//Reference class library

using System.IO;//Reference class library

 public RawImage rawImg;

    public Slider slider;

    public Button button;

    string moveUrl = "http://www.unity3d.com/webplayers/Movie/sample.ogg";//Video download path

    string filePath = string.Empty; //Path used to store local files

   

    MovieTexture mt;//Video texture

    AudioSource aud;//Sound component

    void Start () {

        //mt = new MovieTexture();

        aud = GetComponent<AudioSource>();

        filePath =Application.dataPath + "/Resources/myMovie.ogg";

        button.onClick.RemoveAllListeners();

        button.onClick.AddListener(StartDownLoadAction);

    }

    //Click the time to start the download

    //If it is played locally, it will be played directly, otherwise it will be downloaded

    public void StartDownLoadAction() {

        //Determine whether the video asking price exists locally, play it when it is local, and download it when it is not there

        bool isExisits=File.Exists(filePath);

        if (isExisits)

        {

            //play

            StartCoroutine("PlayMovie");

        }

        else {

            //download

            button.interactable = false;

            StartCoroutine("DownLoadMovie");

        }

    }

    IEnumerator PlayMovie() {

        WWW www = new WWW("file://" + Application.dataPath + "/Resources/myMovie.ogg");

        yield return www;

        while (!www.GetMovieTexture().isReadyToPlay)

        {

            yield return null;

        }

        mt = www.GetMovieTexture();

        print(mt.name + "-----------------");

        rawImg.texture = mt;

        aud.clip = mt.audioClip;

        mt.loop = true;

        mt.Play();

        aud.Play();

    }

    IEnumerator DownLoadMovie()

    {

        WWW www = new WWW (moveUrl);

        while (!www.isDone) {

           slider.value= www.progress;

            yield return null;

        }

        //Write to local. Write the read file to the local through File.WriteAllBytes

        File.WriteAllBytes(filePath, www.bytes);

        button.interactable = true;//Restore the interactive function of the button

        UnityEditor.AssetDatabase.Refresh();//Refresh the folder

        StartCoroutine("PlayMovie");//Start the playback coroutine

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324398781&siteId=291194637