简单封装了一个下载类,记录一下
/// <summary>
/// 异步设置图片
/// </summary>
private void SetAsyncImage(string url, Image image)
{
////是否第一次加载
if (!File.Exists(Path + ImagePath + url.GetHashCode()))
{
StartCoroutine(LoadWebImage(url, image));
}
else
{
StartCoroutine(LoadLocalImage(url, image));
}
}
/// <summary>
/// 加载网图
/// </summary>
IEnumerator LoadWebImage(string url, Image image)
{
if (url != "" || image != null)
{
// UnityEngine.Debug.Log(url);
WWW www = new WWW(url);
yield return www;
if (string.IsNullOrEmpty( www.error))
{
try
{
Texture2D tex2d = www.texture;
if (tex2d != null)
{
//保存图片
byte[] pngData = tex2d.EncodeToPNG();
File.WriteAllBytes(Path + ImagePath + url.GetHashCode(), pngData);
Sprite m_sprite = Sprite.Create(tex2d, new Rect(0, 0, tex2d.width, tex2d.height), Vector2.zero);
image.sprite = m_sprite;
}
else
{
UnityEngine.Debug.LogError("LoadWebImage Texture2D null" + " url=" + url);
}
}
catch (System.Exception error)
{
UnityEngine.Debug.LogError("LoadWebImage exception:"+error + " url=" + url);
}
}
else
{
UnityEngine.Debug.LogError("LoadWebImage error:"+www.error + " url="+ url);
}
}
}
/// <summary>
/// 从本地加载图片
/// </summary>
IEnumerator LoadLocalImage(string url, Image image)
{
string filePath = "file:///" + Path + ImagePath + url.GetHashCode();
if (url != "" || image != null)
{
WWW www = new WWW(filePath);
yield return www;
if (string .IsNullOrEmpty( www.error) )
{
Texture2D texture = www.texture;
if (texture != null)
{
Sprite m_sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
image.sprite = m_sprite;
}
else
{
UnityEngine.Debug.LogError("LoadLocalImage Texture2D null" + " url=" + url);
}
}
else
{
UnityEngine.Debug.LogError("LoadLocalImage error:"+www.error + " url=" + url);
}
}
}
/// <summary>
// 音效
/// </summary>
IEnumerator LoadLocalMusic(string url, AudioSource source)
{
string filePath = "file:///" + Path + AudioPath + url.GetHashCode() + suffix;
if (url != "" || source != null)
{
WWW www = new WWW(filePath);
yield return www;
if (www.error == null)
{
AudioClip clip = www.GetAudioClip();
if (clip != null)
{
source.clip = clip;
source.Play();
}
else
{
UnityEngine.Debug.LogError("LoadLocalMusic:" + "clip null " + " url=" + url);
}
}
else
{
UnityEngine.Debug.LogError("LoadLocalMusic:" + www.error + " url=" + url);
}
}
}
IEnumerator LoadWebMusic(string url, AudioSource source)
{
if (url != "")
{
WWW www = new WWW(url);
yield return www;
if (www.error == null)
{
try
{
AudioClip clip = www.GetAudioClip();
if (clip != null)
{
File.WriteAllBytes(Path + AudioPath + url.GetHashCode() + suffix, www.bytes);
source.clip = clip;
source.Play();
}
else
{
UnityEngine.Debug.LogError("LoadWebMusic:clip null");
}
}
catch (System.Exception error)
{
UnityEngine.Debug.LogError("LoadWebMusic:" + error + " url=" + url);
throw error;
}
}
else
{
UnityEngine.Debug.LogError("LoadWebMusic:" + www.error + " url=" + url);
}
}
}
网友评论