当前位置:网站首页>Unity learning day14 -- collaboration and WWW

Unity learning day14 -- collaboration and WWW

2022-06-23 12:39:00 First wife ash yuanai

 

coroutines IEnomerator


1.yield return Stop the program , Wait until the current frame ends , Continue at the next frame
   yield break End of Association
2.StartCoroutine()   Start the coroutines
3.yield return new WaitForEndOfFrame()   At the next frame OnGUI After the execution, resume the execution
4.yield return new WaitForSeconds(n)   Stop the program , etc. n Seconds later
5.yield return new WaitForFixedUpdate() stay FixedUpdate After performing
6.yield return StartCoroutine( Another process )   Coroutines nesting , Execute the current process after another process is completed

How to start the process :3 Heavy haul
StartCoroutine( The name of the project ( Co process parameters ))
StartCoroutine(" Method name ")
StartCoroutine(" Method name ", Method parameter ) Start the process in this way , The parameter can only be one

The way to stop the process :
StopCoroutine(Coroutine)   Coroutine Is the value object returned by the coroutine
StopCoroutine(IEnumerator)  IEnumerator Is a coroutine interface object
StopCoroutine(" Co process method name ")   This method can only stop the coroutine starting with a string , This is the second startup process
StopAllCoroutines           Stop all processes - Use with caution

Jump out of the process :
yield break

Special synergy
IEnumerator Start() take Start Transform it into a collaborative process Start automatically at the beginning of the game

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

public class IEDemo : MonoBehaviour
{
    int NormalFunction()
    {
        //return The meaning is 【 Return results , And end the execution of the function 】
        return 1;
    }
    
    // Collaborative process  --> 【 Special return value type (Ienumerator Methods 】
    IEnumerator IEnumeratorDemo()
    {
        Debug.Log("1");
        
        // The return value of a coroutine is the same as that of a common method 【 difference 】
        // The biggest difference between , When a coroutine returns the keyword used [yield return]
        // Anything can be returned 
        // In the process of cooperation [ At least once ] Of yield return 
        //yield return [ Known values or variables ]  The meaning is 
        //【 Pause method execution , Wait for the end of the current frame , Wait for the next frame to continue 】
        yield return 1;
        Debug.Log(2);
        // Stop the process 
        yield break;
        // Pause 
        yield return null;
        Debug.Log(3);
        // Pause 
        yield return "abc";
        Debug.Log(4);
    }

    IEnumerator WaitForSecondsDemo()
    {
        Debug.Log("Dog");
        
        // meaning : Stop the program , etc. 3 Seconds later , Keep going 
        yield return  new WaitForSeconds(3);
        
        Debug.Log("Cat");
    }
    
    IEnumerator WaitForEndOfFrameDemo()
    {
        Debug.Log("abc");

        // At the next frame Update After the execution, resume the execution 
        //yield return null;
        // meaning : Stop the program , Wait for the next frame to continue 
        // At the next frame OnGUI After the execution, resume the execution 
        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)
        {
            // Execute function 
            method();
            // Waiting time 
            yield return new WaitForSeconds(seconds);
        }
    }

    IEnumerator InvokeMethodPerFrame(Action method)
    {
        while (true)
        {
            method();
            yield return 0;
        }
    }
    private void Start()
    {
        // Call ordinary functions 
        NormalFunction();
        
        // Start the collaboration program 
        // The first way to write it 
        //StartCoroutine(IEnumeratorDemo());
        // The second way , Write separately 
        /*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 The way : The information parameters are displayed in URL in

Post The way : Parameter information is not displayed in URL in

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(" Original component ")]
    public RawImage _rawImage;
    [Header("Image Components ")]
    public Image _image;
    [Header(" Video player ")]
    public VideoPlayer _VideoPlayer;

    // Declare a video clip 
    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>
    ///  Download the text 
    /// </summary>
    /// <returns></returns>
    IEnumerator DownloadNewsText()
    {
        WWW www = new WWW("http://v.juhe.cn/toutiao/index?type=top&key=bd6d102ed7d4cdbe209c05d413eedcd3");
        // Waiting for download , The first one is 
        yield return www;
        
        // Print the results 
        Debug.Log(www.text);
    }

    /// <summary>
    ///  New version download video 
    /// </summary>
    /// <returns></returns>
    IEnumerator NewVersionDownloadVideo()
    {
        // Try loading the video clip 
        _videoClip = Resources.Load<VideoClip>("welcome");
        // If not loaded to , Then go to download 
        if (_videoClip==null)
        {
            // Create a network request object 
            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");
            // Send network request , And wait for download 
            webRequest.SendWebRequest();

            while (!webRequest.isDone)
            {
                Debug.Log(webRequest.downloadProgress);
                yield return 0;
            }
            
            // Get byte stream of video file 
            byte[] bytes = webRequest.downloadHandler.data;
            
            // Write to local 
            File.WriteAllBytes(Application.dataPath + "/Resources/welcome.mp4",bytes);

            while (_videoClip == null)
            {
                // Refresh resources 
                AssetDatabase.Refresh();
                
                // Try loading the video clip 
                _videoClip = Resources.Load<VideoClip>("welcome");
                
                yield return 0;
            }
        }
        
        // Will be a good video , Set to ViedeoPlayer In the component 
        _VideoPlayer.clip = _videoClip;
        
        // Play the video 
        _VideoPlayer.Play();

    }
    /// <summary>
    ///  New version download 
    /// </summary>
    /// <returns></returns>
    ///  First step 、 Create objects :UnityWebRequest
    /// Get:UnityWebRequest.Get(url)
    /// Post:UnityWebRequest.Post(url, parameter list )
    ///  The second step 、 send out web situation , And wait for download 
    /// yield return data.SendWebRequest();
    ///  The third step 、 Get downloaded content 
    ///  Content classification : Text Text  Direct use ;  Byte stream Bytes  Need to write to local file 
    ///  Step four 、 How to write to local 
    /// File.WriteAllBytes( The full path to the file , Bit array )
    /// 【 Example 】
    /// File.WriteAllBytes(Application.dataPath + "/a.text",bytes);
    ///  Step five 、 How to get files locally 
    /// 1. file 
    IEnumerator NewVisonDownload()
    {
        UnityWebRequest data = UnityWebRequest.Get("http://v.juhe.cn/toutiao/index?type=top&key=bd6d102ed7d4cdbe209c05d413eedcd3");
        // send out web request , And wait for download 
        yield return data.SendWebRequest();
        
        // data 【 Byte stream 】
        byte[] bytes = data.downloadHandler.data;
        
        // Write byte stream to local Resources In the folder 
        File.WriteAllBytes(Application.dataPath + "/Resources/a.text",bytes);

        // Wait a frame 
        yield return 0;
        
        // Refresh resources 
        AssetDatabase.Refresh();
        
        // from Resources Read files in the folder 
        Resources.Load<Text>("a");
        
        
    }
    
    /// <summary>
    ///  Download the pictures 
    /// </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");

        // The second kind , Waiting for download 
        while (!www.isDone)
        {
            Debug.Log("progress:" + www.progress);
            yield return 0;
        }
        /*// Waiting for download 
        yield return www;*/

        #region  Use the texture directly RawImage Rendering 

        // Set the original width and height of the picture 
        _rawImage.GetComponent<RectTransform>().sizeDelta =
            new Vector2(www.texture.width,www.texture.height);
    
        // Set picture to RawImage in 
        _rawImage.texture = www.texture;

        #endregion

        #region  Use Image To render , Before that, you need to convert the texture into a sprite 

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

        #endregion

        // How to convert textures into sprites 
    }

    /// <summary>
    ///  Download Video 
    /// </summary>
    /// <returns></returns>
    IEnumerator DownloadVideos()
    {
        WWW www = new WWW("");

        yield return www;
        
        //www.get
    }
}

 

原网站

版权声明
本文为[First wife ash yuanai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231202150132.html