• QQ
  • nahooten@sina.com
  • 常州市九洲新世界花苑15-2

游戏开发

U3d WWW实现图片资源保存和本地加载

原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1117/192.html

Unity3d WWW类实现图片资源显示以及保存和本地加载

 

WWW类从网上下载资源,和从本地引用资源很有优势,而我们常州网站设计-幻天网络这篇文章要和大家分享的是使用WWW类实现图片资源显示以及本地加载。

 

直接上代码:

using UnityEngine;

using System.Collections;

using System.IO;

using UnityEditor;

enum GetPicType

    DownLoad = 0,

    LocalLoad,

public class Picture : MonoBehaviour

    //这里是本地的ip地址

    string url = "http://127.0.0.1:80000/1.jpg";

    /// <summary>

    /// 网络下载的图片

    /// </summary>

    private Texture2D img = null;

    /// <summary>

    /// 本地图片

    /// </summary>

    private Texture2D img2 = null;

    private bool downloadOK = false;

    void OnGUI()

   

        if (this.img != null)

            GUI.DrawTexture(new Rect(0, 0, 200, 300), this.img);

        if (this.img2 != null)

            GUI.DrawTexture(new Rect(320, 0, 200, 300), this.img2);

        if (GUI.Button(new Rect(210, 0, 100, 20), "显示网络图片"))

       

                StartCoroutine(this.DownLoadTexture(this.url, GetPicType.DownLoad));

       

        if (GUI.Button(new Rect(210, 50, 100, 20), "显示本地图片"))

       

            if (this.downloadOK)

           

                StartCoroutine(DownLoadTexture("file://" + Application.streamingAssetsPath + "/1.png", GetPicType.LocalLoad));

           

            else

           

                Debug.LogError("没有下载完毕");

           

       

   

    IEnumerator DownLoadTexture(string url, GetPicType getType)

   

        WWW www = new WWW(url);

        Texture2D tempImage;

        yield return www;

        if (www.isDone && www.error == null)

       

            switch (getType)

           

                case GetPicType.DownLoad:

                   

                        this.img = www.texture;

                        tempImage = this.img;

                        Debug.Log(tempImage.width + "  " + tempImage.height);

                        break;

                   

                case GetPicType.LocalLoad:

                    this.img2 = www.texture;

                    tempImage = this.img;

                    Debug.Log(tempImage.width + "  " + tempImage.height);

                    break;

                default:

                    tempImage = null;

                    break;

           

            if (tempImage != null)

           

                byte[] data = tempImage.EncodeToPNG();

                File.WriteAllBytes(Application.streamingAssetsPath + "/1.png", data);

                this.downloadOK = true;

           

       

   



上篇:上一篇:U3D非xml的字符串变规范的xml
下篇:下一篇:Unity真机调试(一)