协程 IEnomerator

1.yield return 暂停协程,等当前帧结束,在下一帧继续执行
   yield break 结束协程
2.StartCoroutine()  启动协程
3.yield return new WaitForEndOfFrame()  在下一帧的OnGUI执行完了恢复继续执行
4.yield return new WaitForSeconds(n)  暂停协程,等n秒后继续执行
5.yield return new WaitForFixedUpdate() 在FixedUpdate之后执行
6.yield return StartCoroutine(另一个协程)  协程嵌套,在另一个协程结束后再执行当前协程

启动协程的方式:3个重载
StartCoroutine(协程名称(协程参数))
StartCoroutine("方法名称")
StartCoroutine("方法名称",方法参数) 用这种方法启动协程,参数只能是一个

停止协程的方式:
StopCoroutine(Coroutine)   Coroutine是协程返回的值对象
StopCoroutine(IEnumerator)  IEnumerator是协程接口对象
StopCoroutine("协程方法名称")  这种方式只能停止以字符串开始的协程,就是第二种启动协程
StopAllCoroutines          停止所有协程-慎用

跳出协程:
yield break

特殊协程
IEnumerator Start() 将Start改造成一个协程 在游戏开始时自动启动

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IEDemo : MonoBehaviour
{
    int NormalFunction()
    {
        //return的含义是【返回结果,并结束函数的执行】
        return 1;
    }
    
    //协同程序 --> 【特殊返回值类型(Ienumerator的方法】
    IEnumerator IEnumeratorDemo()
    {
        Debug.Log("1");
        
        //协程的返回值与普通方法的返回【区别】
        //最大区别,协程返回使用的关键字时[yield return]
        //返回任何东西都可以
        //协程中[至少要有一次]的yield return 
        //yield return [已知值或变量] 的含义是
        //【暂停方法执行,等待当前帧结束,等待下一帧继续执行】
        yield return 1;
        Debug.Log(2);
        //停止协程的运行
        yield break;
        //暂停
        yield return null;
        Debug.Log(3);
        //暂停
        yield return "abc";
        Debug.Log(4);
    }

    IEnumerator WaitForSecondsDemo()
    {
        Debug.Log("Dog");
        
        //含义:暂停协程,等3秒之后,继续进行
        yield return  new WaitForSeconds(3);
        
        Debug.Log("Cat");
    }
    
    IEnumerator WaitForEndOfFrameDemo()
    {
        Debug.Log("abc");

        //在下一帧的Update执行完了恢复继续执行
        //yield return null;
        //含义:暂停协程,等下一帧再继续执行
        //在下一帧的OnGUI执行完了恢复继续执行
        yield return new WaitForEndOfFrame();
        
        Debug.Log("def");
    }

    IEnumerator WaitForSecondCircle()
    {
        int count = 0;
        while (true)
        {
            yield return new WaitForSeconds(1);
            Debug.Log(++count);
        }
    }

    IEnumerator InvokeMethodPerSeconds(Action method,float seconds)
    {
        while (true)
        {
            //执行函数
            method();
            //等待时间
            yield return new WaitForSeconds(seconds);
        }
    }

    IEnumerator InvokeMethodPerFrame(Action method)
    {
        while (true)
        {
            method();
            yield return 0;
        }
    }
    private void Start()
    {
        //调用普通函数
        NormalFunction();
        
        //启动协同程序
        //第一种写法
        //StartCoroutine(IEnumeratorDemo());
        //第二种写法,分开写
        /*IEnumerator ie = IEnumeratorDemo();
        StartCoroutine(ie);*/

        //StartCoroutine(WaitForEndOfFrameDemo());
        //StartCoroutine(WaitForSecondsDemo());
        //StartCoroutine(WaitForSecondCircle());
        /*StartCoroutine(InvokeMethodPerSeconds(() =>
        {
            Debug.Log("Hello World!");
        }, 2f));*/
        StartCoroutine(InvokeMethodPerFrame((() =>
        {
            Debug.Log("Hello Unity!");
        })));
    }

  
}

Get方式:信息参数显示在URL中

Post方式:参数信息不显示在URL中

WWW

using System;
using System.Collections;
using System.IO;
using System.Net;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;

public class WWWDemo : MonoBehaviour
{
    [Header("原图组件")]
    public RawImage _rawImage;
    [Header("Image组件")]
    public Image _image;
    [Header("视频播放器")]
    public VideoPlayer _VideoPlayer;

    //声明一个视频片段
    private VideoClip _videoClip;
    private IEnumerator Start()
    {
        //yield return StartCoroutine(DownLoadText());
        //yield return StartCoroutine(DownloadNewsText());
        //yield return StartCoroutine(DownloadTexture());
       // yield return StartCoroutine(NewVisonDownload());
       yield return StartCoroutine(NewVersionDownloadVideo());
    }

    /// <summary>
    /// 下载文本
    /// </summary>
    /// <returns></returns>
    IEnumerator DownloadNewsText()
    {
        WWW www = new WWW("http://v.juhe.cn/toutiao/index?type=top&key=bd6d102ed7d4cdbe209c05d413eedcd3");
        //等待下载,第一种
        yield return www;
        
        //打印结果
        Debug.Log(www.text);
    }

    /// <summary>
    /// 新版本下载视频
    /// </summary>
    /// <returns></returns>
    IEnumerator NewVersionDownloadVideo()
    {
        //尝试加载视频片段
        _videoClip = Resources.Load<VideoClip>("welcome");
        //如果没有加载到,则去下载
        if (_videoClip==null)
        {
            //创建网络请求对象
            UnityWebRequest webRequest = UnityWebRequest.Get("http://f.video.weibocdn.com/00341gCFgx07LoEZcDa7010412017MOB0E010.mp4?label=mp4_hd&template=852x480.25.0&trans_finger=62b30a3f061b162e421008955c73f536&media_id=4619091051479108&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=3&ot=h&lp=00002KCE4n&ps=4pdsh0&uid=3ZoTIp&ab=3915-g1,966-g1,1493-g0,1192-g0,1191-g0,1046-g2,3601-g5,1258-g0&Expires=1619087600&ssig=V%2FxM%2B1IoMo&KID=unistore,video");
            
            //WebRequest webRequest = WebRequest.Create(
            //"http://f.video.weibocdn.com/00341gCFgx07LoEZcDa7010412017MOB0E010.mp4?label=mp4_hd&template=852x480.25.0&trans_finger=62b30a3f061b162e421008955c73f536&media_id=4619091051479108&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=3&ot=h&lp=00002KCE4n&ps=4pdsh0&uid=3ZoTIp&ab=3915-g1,966-g1,1493-g0,1192-g0,1191-g0,1046-g2,3601-g5,1258-g0&Expires=1619087600&ssig=V%2FxM%2B1IoMo&KID=unistore,video");
            //发送网络请求,并等待下载
            webRequest.SendWebRequest();

            while (!webRequest.isDone)
            {
                Debug.Log(webRequest.downloadProgress);
                yield return 0;
            }
            
            //获取视频文件的字节流
            byte[] bytes = webRequest.downloadHandler.data;
            
            //写入到本地
            File.WriteAllBytes(Application.dataPath + "/Resources/welcome.mp4",bytes);

            while (_videoClip == null)
            {
                //刷新资源
                AssetDatabase.Refresh();
                
                //尝试加载视频片段
                _videoClip = Resources.Load<VideoClip>("welcome");
                
                yield return 0;
            }
        }
        
        //将下好的视频,设置到ViedeoPlayer组件中
        _VideoPlayer.clip = _videoClip;
        
        //播放视频
        _VideoPlayer.Play();

    }
    /// <summary>
    /// 新版本下载
    /// </summary>
    /// <returns></returns>
    /// 第一步、创建对象:UnityWebRequest
    /// Get:UnityWebRequest.Get(url)
    /// Post:UnityWebRequest.Post(url,参数列表)
    /// 第二步、发送web情况,并等待下载
    /// yield return data.SendWebRequest();
    /// 第三步、获取下载好的内容
    /// 内容分类:文本Text 直接用; 字节流Bytes 需要写入本地文件
    /// 第四步、如何写入到本地
    /// File.WriteAllBytes(文件的完整路径,比特数组)
    /// 【示例】
    /// File.WriteAllBytes(Application.dataPath + "/a.text",bytes);
    /// 第五步、如何从本地获取文件
    /// 1.文件
    IEnumerator NewVisonDownload()
    {
        UnityWebRequest data = UnityWebRequest.Get("http://v.juhe.cn/toutiao/index?type=top&key=bd6d102ed7d4cdbe209c05d413eedcd3");
        //发送web请求,并等待下载
        yield return data.SendWebRequest();
        
        //数据【字节流】
        byte[] bytes = data.downloadHandler.data;
        
        //将字节流写入到本地Resources文件夹中
        File.WriteAllBytes(Application.dataPath + "/Resources/a.text",bytes);

        //等一帧
        yield return 0;
        
        //刷新资源
        AssetDatabase.Refresh();
        
        //从Resources文件夹中读取文件
        Resources.Load<Text>("a");
        
        
    }
    
    /// <summary>
    /// 下载图片
    /// </summary>
    /// <returns></returns>
    IEnumerator DownloadTexture()
    {
        WWW www = new WWW("https://th.bing.com/th/id/R65398d6ad86129f9628c0ad80da4040c?rik=C3qNS9mZOQk%2b5A&riu=http%3a%2f%2fwww.shijuepi.com%2fuploads%2fallimg%2f200918%2f1-20091Q10420.jpg&ehk=QBNuJIbVP1qo%2bwUD3YzXcvL4H5iHivOHXUnzzRw%2bWfU%3d&risl=&pid=ImgRaw");

        //第二种,等待下载
        while (!www.isDone)
        {
            Debug.Log("progress:" + www.progress);
            yield return 0;
        }
        /*//等待下载
        yield return www;*/

        #region 直接将纹理用RawImage进行渲染

        //设置图片的原始宽高
        _rawImage.GetComponent<RectTransform>().sizeDelta =
            new Vector2(www.texture.width,www.texture.height);
    
        //设置图片到RawImage中
        _rawImage.texture = www.texture;

        #endregion

        #region 使用Image去渲染,在此之前要将纹理转换为精灵

        Sprite sprite = Sprite.Create(www.texture, new Rect(
                Vector2.zero,
                new Vector2(www.texture.width,
                    www.texture.height)),
            Vector2.zero
        );
        sprite.name = "sprite";
        //渲染
        _image.sprite = sprite;

        #endregion

        //如何把纹理转换成精灵
    }

    /// <summary>
    /// 下载视频
    /// </summary>
    /// <returns></returns>
    IEnumerator DownloadVideos()
    {
        WWW www = new WWW("");

        yield return www;
        
        //www.get
    }
}