unity3d WWW类的简单使用

WWW类可以下载服务器上面的资源,也可以下载本地资源。

首先创建场景,创建一个Cube,搭载界面,两个Button.

unity3d WWW类的简单使用

 在Cube上添加脚本,内容如下:

  1.     private Texture text0;//下载本地图片
  2.     private Texture text1;//下载网络上的图片
  3.     public Button but1;//本地Button
  4.     public Button but2;//网络Button
  5.     private void Start()
  6.     {
  7.         but1 = GameObject.Find("Button1").GetComponent<Button>();//获取button1组件
  8.         but1.onClick.AddListener(OnBut1);//绑定点击事件
  9.         but2 = GameObject.Find("Button2").GetComponent<Button>();//获取button2组件
  10.         but2.onClick.AddListener(OnBut2);//绑定点击事件
  11.     }
  12.     void OnBut1() {//Button1的点击事件
  13.         StartCoroutine(LoadLocal());//开启下载本地资源的协程
  14.     }
  15.     void OnBut2() {//Button2的点击事件
  16.         StartCoroutine(LoadNetWork());//开启下载网络资源的协程
  17.     }
  18.     IEnumerator LoadLocal ()//下载本地资源的协程
  19.     {
  20.         if (text0 == null) {
  21.            //使用www类下载本地资源的图片     本地资源路径
  22.             WWW date = new WWW ("file://" + Application.dataPath + "/Texture/down.png");
  23.             yield return date;
  24.             text0 = date.texture;//给text0赋值
  25.         }
  26.          给Cube的material的texture赋值
  27.         GameObject.Find ("Cube").GetComponent<Renderer> ().material.mainTexture = text0;
  28.     }
  29.     IEnumerator LoadNetWork ()//下载网络图片的协程
  30.     {
  31.         if (text1 == null) {
  32.            //下载网络图片的的资源
  33.             WWW date = new WWW ("http://www.iyi8.com/uploadfile/2017/0903/20170903103644448.jpg");
  34.             yield return date;
  35.             text1 = date.texture;//给text1赋值
  36.         }
  37.         //给Cube的material的texture赋值
  38.         GameObject.Find ("Cube").GetComponent<Renderer> ().material.mainTexture = text1;
  39. }

运行,点击button1,Cube的texture就是本地的资源,点击button2,Cube的texture就是网络上的资源。

网络图片的路径怎么找呢?下面我简单的说一下啊。

随便在网络上找一张图片, 点击图片,鼠标右键属性,就可以找到图片的路径。如下图所示,箭头位置就是图片的路径。

unity3d WWW类的简单使用