天天看點

Unity~ WWW類

什麼是WWW類

www就是網絡工具類,Unity用于從網絡上下載下傳需要的檔案,包括音頻,視訊,圖檔等檔案的工具類.

HTTP 超文本傳輸協定,網絡傳輸協定,伺服器之間檔案傳輸的規範

HTTP中的方法

<1>GET 擷取伺服器資料

<2>POST 上傳資料到伺服器

<3>PUT 修改資料

<4>DELETE 删除資料

www路徑:

<1>http://網址 (網絡請求,網絡傳輸協定)

<2>https://網址 (網絡請求,網絡傳輸協定)

<3>file://本地檔案位址 (本地請求,本地檔案傳輸協定)

使用WWW類下載下傳網絡視訊并在Unity中播放

<一般作為遊戲的CG動畫,和遊戲中的廣告植入等>

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System;

public class VideosScript : MonoBehaviour {

    RawImage _immage;
    //定義變量路徑
    string vedioURL;
    //本地路徑,前面要三個斜杠.前兩個表示本地 後一個斜杠表示電腦中的路徑
    //string _voideoURL = "file:///C:/Users/aixia/Desktop";
    void Start () {
        //視訊路徑 (這裡部落客沒找到适合的視訊網站。。。。。倍感失敗)
        vedioURL = "https://www.bilibili.com/5de0d107-7802-4c24-9473-3a085e451f32";

        //圖檔路徑
         string url = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1345734636,1096966958&fm=26&gp=0.jpg";
        //開啟協程 下載下傳圖檔
         StartCoroutine (IEPhoto (url));
        //開啟協程下載下傳視訊
        //StartCoroutine (IEvedio (vedioURL));
    }

    #region 圖檔下載下傳


    //用協程異步加載視訊,一般協程都與資源加載連用
    IEnumerator IEPhoto(string url)
    {
        //建立www類,并把路徑作為參數傳給www的構造方法
        WWW www = new WWW (url);
        //www.isDone  該方法傳回值為bool 加載完成的時候傳回true
        while (!www.isDone)
        {
            //該方法用于擷取下載下傳進度,值為0到1
            print( www.progress.ToString());
            yield return www;
            if (LoadImage("MyImage"))
            {
                //File.WriteAllBytes方法将所有從網絡上下載下傳的檔案儲存在本地的位置,并重命名為MyImage.jpg;
                //www.bytes,下載下傳的檔案
                File.WriteAllBytes (Application.dataPath + "/Resources/MyImage.jpg", www.bytes);
                //重新整理Asset檔案夾
                UnityEditor.AssetDatabase.Refresh ( );
            }
        }
    }
    //該方法用于判斷Resources檔案夾中是否存在該圖檔
    private bool LoadImage (string texturename)
    {       
        //如果存在傳回false 就不去下載下傳
        if (Resources.Load(texturename) != null)
        {
            Debug.Log ("圖檔已經存在");
            return false;
        }
        else
        {
            //如果不存在傳回true重新下載下傳
            Debug.Log ("圖檔不存在,開始下載下傳");
            return true;
        }

    }

    #endregion

    //視訊下載下傳

    IEnumerator IEvedio(string url)
    {
        WWW www = new WWW (url);
        while (!www.isDone)
        {
            if (www.progress<)
            {
                yield return ;
                print ( www.progress);
            }
            yield return www;

            File.WriteAllBytes (Application.dataPath+"/Resources/MyVedio.mp4",www.bytes);
            UnityEditor.AssetDatabase.Refresh ( );
        }
    }
}