最近因工作需要做了一个需求如下的功能:从网络下载图片,保存到本地,版本号不同时,更新本地文件,否则每次只从本地读取文件。
1、首先需要三个string类型的变量和一个WWW
WWW www = null;
string m_localPath = string.Format("{0}/LocalDirectory", Application.persistentDataPath);
string m_localKey = "LocalKey";
string m_localFilePath = string.Empty;
UITexture m_texture = null;//这是一个NGUI的UITexture,需要在代码中关联,此处不细表
2、下面介绍具体实现方法
void DownLoadFunction(string url, int version)
{
if(!Directory.Exists(m_localPath))
{
Directory.CreatDirectory(m_localPath);
}
//取文件名
string[] tempArray = url.Split(new char[]{'/'}, StringSplitOptions.RemoveEmptyEntries);
string tempPictureName = string.Empty;
if(tempArray != null)
{
tempPictureName = tempArray[tempArray.Length - 1];
}
m_localFilePath = string.Format("{0}/{1}", m_localPath, tempPictureName);
if(PlayerPerfs.HasKey(m_localKey) && PlayerPrefs.GetInt(m_localKey) == version && File.Exists(m_localFilePath))
{
www = new WWW(GetResDirByPath(m_localFilePath));
}
else
{
www = new WWW(url);
PlayerPrefs.SetInt(m_localKey, version);
}
}
3、下面是一个读取本地文件时的一个路径转换方法
voidGetResDirByPath(string path)
{
string strBaseDir = string.Empty;
if(RuntimePlatform.Android == Application.platform)
{
strBaseDir = "file:///" + path;
}
else if(RuntimePlatform.IPhonePlayer == Application.platform)
{
strBaseDir = "file://" + path;
}
else if(RuntimePlatform.WindowsWebPlayer == Application.platform ||RuntimePlatform.OSXWebPlayer == Application.platform))
{
strBaseDir = path;
}
else
{
strBaseDir = "file:///" + path;
}
return strBaseDir;
}
4、下面是每个游戏中都会存在的Update方法。
void Update()
{
if(www != null)
{
if(www.error != null)
{
Debug.LogError(www.error + "FROM URL:" + www.url);
www = null;
}
else if(www.isDone && www.progress == 1)
{
File.WriteAllBytes(m_localFilePath, www.texture.EncodeToPNG());
m_texture.mainTexture = www.texture;
www.Dispose();
www = null;
}
}
}
5、以上就是针对此功能的主要功能代码,部分内容需要自己去查找和理解