1、线程下载
代码
- using System.IO;
- using System.Net;
- using UnityEngine;
- using System.Threading;
- using System.Collections;
- public class ThreadTest : MonoBehaviour {
- private string[] _urls = new string[10];
- private string[] _localPath = new string[10];
- // Use this for initialization
- void Start ()
- {
- for (int i = 0; i < _urls.Length; i++)
- {
- //所有图片的下载地址
- _urls[i] = "http://192.168.1.41:8080/Test/picture/" + (i + 1).ToString() + ".jpg";
- //所有图片的保存路径
- _localPath[i] = Application.dataPath + "/Resources/" + (i + 1).ToString() + ".jpg";
- MyThread mt = new MyThread(_urls[i], _localPath[i]);
- Thread thread = new Thread(new ThreadStart(mt.DownLoadImage));
- thread.Start();
- }
- }
- // Update is called once per frame
- void Update ()
- {
- }
- void OnGUI()
- {
- }
- }
- public class MyThread
- {
- public string _url;
- public string _filePath;
- public MyThread(string url, string filePath)
- {
- _url = url;
- _filePath = filePath;
- }
- public void DownLoadImage()
- {
- WebClient web = new WebClient();
- web.DownloadFile(_url, _filePath);
- }
- }
2、批量下载
代码如下
- using System.IO;
- using UnityEngine;
- using System.Net;
- using System.Collections;
- public class Test : MonoBehaviour {
- private string[] _urls=new string[10];
- private string [] _localPath = new string[10];
- // Use this for initialization
- void Start ()
- {
- for (int i = 0; i < _urls.Length; i++)
- {
- //所有图片的下载地址
- _urls[i] = "http://192.168.1.41:8080/Test/picture/" + (i + 1).ToString() + ".jpg";
- //所有图片的保存路径
- _localPath[i] = Application.dataPath + "/Resources/" + (i + 1).ToString() + ".jpg";
- }
- }
- // Update is called once per frame
- void Update()
- {
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(0, 0, 100, 30), "下载所有图片"))
- {
- DownLoad();
- }
- //判断文件是否已下载
- for (int i = 0; i < _urls.Length; i++)
- {
- if (File.Exists(_localPath[i]))
- {
- GUI.Button(new Rect(0, 30 * i+30, 50, 30), (i + 1).ToString());
- }
- }
- }
- //下载所有图片
- private void DownLoad()
- {
- for (int i = 0; i < _urls.Length; i++)
- {
- DownLoadAllImages(_urls[i], _localPath[i]);
- }
- }
- void DownLoadAllImages(string url, string localPath)
- {
- WebClient web = new WebClient();
- web.DownloadFile(url, localPath);
- //以下代码下载完成后执行
- }
- }
-
-
-
原文链接:
http://blog.csdn.net/awnuxcvbn/article/details/9246633版权声明:本文为博主原创文章,未经博主允许不得转载。