前置知识:
post请求指的是网址中后面有问号的,问号后面是参数,用&符号连接
get请求指的是通过网站访问再加上一个用于存储参数的表单来向服务器发出请求
www可以再unity中根据不同前缀下载不同文件
IOS:
File://
Android:
Jar:file://
PC:
File:///
如何应用: 判断是Applictation.plantform是什么平台,来把给url加上对应的前缀
位置分为:
Application.dataPath:只能在PC中访问工程文件 可读
Application.persistentDataPath:用文件系统(File/Streamreader/streamwriter) 可读可写
Application.streamingAssetsPath:都会打包到app包然后处于真机该路径中:assets\streamingAssets 只能用www读取
综上,网络内的东西(streamingAssets),只能通过www读取拷贝到Application.persistentDataPath内部,然后通过文件系统读取和写入
Android:SD卡
IOS:Document
PC:C:\\User\yujie\AppData
网络游戏一进去,一般会检查更新,如果有更新那么就会从服务器下载文件,更新游戏,现在开始封装模块.
首先第一步了解分析需求:
制作并封装一个WWW的框架,用于下载与更新游戏内容;
1.http请求:post,get
2.下载本地文件
画图:
实现:
/// <summary>
/// 任务下载基类(底层代码) 应包含:1.下载开始,下载结束,下载出错时对应方法 2.下载地址url 3.下载方法
/// </summary>
public class WWWIterm
{
public virtual void BeginDownload() { }
public virtual void FinishDownload(WWW www) { }
public virtual void ErrorDownload(WWWIterm tempIterm) { }
private string url;
public string URL
{
get
{
return url;
}
set
{
url = value;
}
}
public IEnumerator Download()
{
BeginDownload();
WWW www = new WWW(URL);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
FinishDownload(www);
}
else
{
ErrorDownload(this);
}
}
}
/// <summary>
/// 需要下载的文件 第二层代码继承了底层的基类WWWiterm
/// </summary>
public class WWWTxt : WWWIterm
{
public WWWTxt(string url)
{
Initial(url);
}
public void Initial(string url)
{
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer)
{
this.URL += "file:///" + url;
}
else if (Application.platform == RuntimePlatform.Android)
{
this.URL = "jar:file//" + url;
}
else
{
this.URL = "file://" + url;
}
}
public override void BeginDownload()
{
// base.BeginDownload();
Debug.Log("Begin download!");
}
public override void ErrorDownload(WWWIterm tempIterm)
{
//base.ErrorDownload(tempIterm);
//下载出错了就继续放进下载队列,直到下载完成
WWWHelper.Instance.AddTask(tempIterm);
}
public override void FinishDownload(WWW www)
{
//base.FinishDownload(www);
Debug.Log("下载完成了==" + www.text);
//TODO: 解析 解压
}
}
/// <summary>
/// 下载助手 需要包含下载队列 是一个策略设计模式
/// </summary>
public class WWWHelper : MonoBehaviour
{
public static WWWHelper Instance;
Queue<WWWIterm> allTask;
private void Start()
{
Instance = this;
allTask = new Queue<WWWIterm>();
}
IsDownloadingFinish = true;
public void AddTask(WWWIterm iterm)
{
//将任务放入队列中
allTask.Enqueue(iterm);
if(allTask.Count > 0 && IsDownloadingFinish)
{
IsDownloadingFinish = false;
StartCoroutine(DownloadIterm());
}
}
public IEnumerator DownloadIterm()
{
while (allTask.Count > 0)
{
//将任务拿出队列(头部)
WWWIterm iterm = allTask.Dequeue();
//相当于for循环套用for循环(携程内套了另一个携程)
yield return iterm.Download();
IsDownloadingFinish = ture;
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
//使用起来只需要这三步
string url = Application.dataPath + "/WWW/WWWTxtcs";
WWWTxt tempText = new WWWTxt(url);
WWWHelper.Instance.AddTask(tempText);
}
}
}