当前位置:   article > 正文

Unity 工具类 之 简单网络下载任务队列服务实现(WWW/UnityWebRequest/下载AssetBundle/Audioclip/Texture2D/Text等)_unity besthttp 下载audioclip

unity besthttp 下载audioclip

 

Unity 工具类 之 简单网络下载任务队列服务实现(WWW/UnityWebRequest/下载AssetBundle/Audioclip/Texture2D/Text等)

 

目录

Unity 工具类 之 简单网络下载任务队列服务实现(WWW/UnityWebRequest/下载AssetBundle/Audioclip/Texture2D/Text等)

一、简单介绍

二、实现原理

三、效果预览

四、实现步骤

五、关键代码


 

一、简单介绍

Unity 工具类,自己整理的一些游戏开发可能用到的模块,单独独立使用,方便游戏开发。

简单网络下载任务队列服务,单独做了一个单例类,实现向服务中添加任务,就会自动下载对应的下载任务,可以根据自己的需要添加自己下载后的资源管理,以及扩展其他下载类型的任务和功能,供外界调用。

 

二、实现原理

1、IWWWBase 和 WWWBase ,作为具体的下载类型基类,定义共有方法和属性;

2、WWWAudio 、WWWImage 实现具体类型下载方法和开始下载、下载错误、下载完成的事件(根据需要可以自行拓展);

3、WWWService 负责添加下载任务,并自动下载对应下载任务;

4、简单网络下载任务队列服务 大概的框架如下:

 

 

三、效果预览

 

四、实现步骤

1、打开Unity,新建一个空工程

 

2、在场景中添加 RawImage和Text 用显示下载的图片的和Text文本

 

3、新建脚本,实现各个类型下载,以及 下载服务类,添加任务下载,和一个测试功能的脚本

 

4、把测试脚本对应添加到场景中,并对应的赋值

 

5、运行脚本,会有图片显示、文本显示,以及一个音频播放

6、断网的时候,结果如下

 

五、关键代码

1、TestWWWService

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TestWWWService : MonoBehaviour
  6. {
  7. public RawImage rawImage;
  8. public Text text;
  9. AudioSource audioSource;
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. audioSource =this.gameObject.AddComponent<AudioSource>();
  14. Test();
  15. }
  16. void Test() {
  17. string imageUrl = @"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1752460159,226752426&fm=26&gp=0.jpg";
  18. WWWImage wImage = new WWWImage(imageUrl,
  19. (texture)=> {
  20. rawImage.texture = (Texture2D)texture;
  21. if (WWWService.Instance.wImageDic.ContainsKey(imageUrl) == false)
  22. {
  23. WWWService.Instance.wImageDic.Add(imageUrl, (Texture2D)texture);
  24. }
  25. });
  26. string audioUrl = @"http://downsc.chinaz.net/Files/DownLoad/sound1/201702/8369.wav";
  27. WWWAudio wAudio = new WWWAudio(audioUrl,
  28. (clip) =>{
  29. audioSource.clip = (AudioClip)clip;
  30. audioSource.Play();
  31. if (WWWService.Instance.wAudipDic.ContainsKey(audioUrl) == false)
  32. {
  33. WWWService.Instance.wAudipDic.Add(audioUrl, (AudioClip)clip);
  34. }
  35. });
  36. string txtUrl = @"http://baidu.com";
  37. WWWText wText = new WWWText(txtUrl,
  38. (txt)=>{
  39. text.text = (string)txt;
  40. if (WWWService.Instance.wTextDic.ContainsKey(txtUrl) == false)
  41. {
  42. WWWService.Instance.wTextDic.Add(txtUrl, (string)txt);
  43. }
  44. });
  45. WWWService.Instance.AddWWWTask(wImage);
  46. WWWService.Instance.AddWWWTask(wAudio);
  47. WWWService.Instance.AddWWWTask(wText);
  48. }
  49. }

 

2、WWWService

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class WWWService : MonoSingleton<WWWService>
  5. {
  6. // 下载队列
  7. private Queue<WWWBase> allWWWTaskQue = new Queue<WWWBase>();
  8. #region 数据管理
  9. internal Dictionary<string, string> wTextDic = new Dictionary<string, string>();
  10. internal Dictionary<string, Texture2D> wImageDic = new Dictionary<string, Texture2D>();
  11. internal Dictionary<string, AudioClip> wAudipDic = new Dictionary<string, AudioClip>();
  12. #endregion
  13. #region 下载任务
  14. public void AddWWWTask(WWWBase task) {
  15. Debug.Log(GetType()+ "/AddWWWTask() Add One WWW Task/");
  16. allWWWTaskQue.Enqueue(task);
  17. // 有开始下载
  18. if (allWWWTaskQue.Count == 1)
  19. {
  20. // 协程开始任务下载
  21. StartCoroutine(DownloadWWWTask());
  22. }
  23. }
  24. IEnumerator DownloadWWWTask() {
  25. // 循环到下载完为止
  26. while (allWWWTaskQue.Count > 0)
  27. {
  28. WWWBase task = allWWWTaskQue.Dequeue();
  29. // 等待这个任务下载完
  30. yield return task.Download();
  31. }
  32. }
  33. #endregion
  34. }

 

3、IWWWBase

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;
  5. public interface IWWWBase
  6. {
  7. //开始下载
  8. void BeginDownload();
  9. // 下载出错
  10. void DownloadError(UnityWebRequest uwr);
  11. // 下载结束
  12. void DownloadFinish(UnityWebRequest uwr);
  13. // 协程下载
  14. IEnumerator Download();
  15. }

 

4、WWWBase

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. public class WWWBase : IWWWBase
  7. {
  8. private string url;
  9. public string Url { get => url; set => url = value; }
  10. protected Action<object> action;
  11. public WWWBase(string url, Action<object> action = null)
  12. {
  13. Url = url;
  14. this.action = action;
  15. }
  16. public virtual void BeginDownload()
  17. {
  18. }
  19. public virtual void DownloadError(UnityWebRequest uwr)
  20. {
  21. }
  22. public virtual void DownloadFinish(UnityWebRequest uwr)
  23. {
  24. }
  25. public virtual IEnumerator Download()
  26. {
  27. BeginDownload();
  28. using (UnityWebRequest uwr = UnityWebRequest.Get(Url))
  29. {
  30. yield return uwr.SendWebRequest();
  31. if (!(uwr.isNetworkError || uwr.isHttpError))
  32. {
  33. DownloadFinish(uwr);
  34. }
  35. else
  36. {
  37. DownloadError(uwr);
  38. }
  39. }
  40. }
  41. }

 

5、WWWAudio

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. public class WWWAudio : WWWBase
  7. {
  8. // 最好构建资源管理统一放置
  9. public AudioClip clip;
  10. public WWWAudio(string url, Action<object> action = null) : base(url, action)
  11. {
  12. }
  13. public override void BeginDownload()
  14. {
  15. Debug.Log(GetType()+ "/BeginDownload()/ Audio");
  16. }
  17. public override void DownloadError(UnityWebRequest uwr)
  18. {
  19. Debug.Log(GetType() + "/BeginDownload()/ Audio uwr.error : " + uwr.error);
  20. }
  21. public override void DownloadFinish(UnityWebRequest uwr)
  22. {
  23. clip = DownloadHandlerAudioClip.GetContent(uwr);
  24. action?.Invoke(clip);
  25. }
  26. public override IEnumerator Download()
  27. {
  28. BeginDownload();
  29. using (var uwr = UnityWebRequestMultimedia.GetAudioClip(Url, AudioType.WAV))
  30. {
  31. yield return uwr.SendWebRequest();
  32. if (!(uwr.isNetworkError || uwr.isHttpError))
  33. {
  34. DownloadFinish(uwr);
  35. }
  36. else
  37. {
  38. DownloadError(uwr);
  39. }
  40. }
  41. }
  42. }

 

6、WWWImage

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. public class WWWImage : WWWBase
  7. {
  8. // 最好构建资源管理统一放置
  9. public Texture2D texture2D;
  10. public WWWImage(string url , Action<object> action = null):base(url,action)
  11. {
  12. }
  13. public override void BeginDownload()
  14. {
  15. Debug.Log(GetType() + "/BeginDownload()/ Image");
  16. }
  17. public override void DownloadError(UnityWebRequest uwr)
  18. {
  19. Debug.Log(GetType() + "/BeginDownload()/ Image uwr.error : " + uwr.error);
  20. }
  21. public override void DownloadFinish(UnityWebRequest uwr)
  22. {
  23. texture2D = ((DownloadHandlerTexture)uwr.downloadHandler).texture;
  24. action?.Invoke(texture2D);
  25. }
  26. public override IEnumerator Download()
  27. {
  28. BeginDownload();
  29. using (UnityWebRequest uwr = new UnityWebRequest(Url))
  30. {
  31. DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
  32. uwr.downloadHandler = downloadTexture;
  33. yield return uwr.SendWebRequest();
  34. if (!(uwr.isNetworkError || uwr.isHttpError))
  35. {
  36. DownloadFinish(uwr);
  37. }
  38. else
  39. {
  40. DownloadError(uwr);
  41. }
  42. }
  43. }
  44. }

 

7、WWWText

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEngine;
  6. using UnityEngine.Networking;
  7. public class WWWText : WWWBase
  8. {
  9. // 最好构建资源管理统一放置
  10. public string txtStr;
  11. public WWWText(string url, Action<object> action = null) : base(url, action)
  12. {
  13. }
  14. public override void BeginDownload()
  15. {
  16. Debug.Log(GetType() + "/BeginDownload()/ Text");
  17. }
  18. public override void DownloadError(UnityWebRequest uwr)
  19. {
  20. Debug.Log(GetType() + "/BeginDownload()/ Text uwr.error : " + uwr.error);
  21. }
  22. public override void DownloadFinish(UnityWebRequest uwr)
  23. {
  24. txtStr = uwr.downloadHandler.text;
  25. action?.Invoke(txtStr);
  26. }
  27. public override IEnumerator Download()
  28. {
  29. BeginDownload();
  30. using (UnityWebRequest uwr = UnityWebRequest.Get(Url)) {
  31. yield return uwr.SendWebRequest();
  32. if (!(uwr.isNetworkError || uwr.isHttpError))
  33. {
  34. DownloadFinish(uwr);
  35. }
  36. else
  37. {
  38. DownloadError(uwr);
  39. }
  40. // 保存本地(酌情处理)
  41. //File.WriteAllText(@"D:\xxxx.txt", str);
  42. }
  43. }
  44. }

 

8、WWWAssetBundle

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. public class WWWAssetBundle : WWWBase
  7. {
  8. // 最好构建资源管理统一放置
  9. public AssetBundle assetBundle;
  10. public WWWAssetBundle(string url, Action<object> action = null) : base(url, action)
  11. {
  12. }
  13. public override void BeginDownload()
  14. {
  15. Debug.Log(GetType() + "/BeginDownload()/ AssetBundle");
  16. }
  17. public override void DownloadError(UnityWebRequest uwr)
  18. {
  19. Debug.Log(GetType() + "/BeginDownload()/ AssetBundle uwr.error : " + uwr.error);
  20. }
  21. public override void DownloadFinish(UnityWebRequest uwr)
  22. {
  23. assetBundle = ((DownloadHandlerAssetBundle)uwr.downloadHandler).assetBundle;
  24. }
  25. public override IEnumerator Download()
  26. {
  27. BeginDownload();
  28. using (UnityWebRequest uwr = new UnityWebRequest(Url))
  29. {
  30. DownloadHandlerAssetBundle handler = new DownloadHandlerAssetBundle(uwr.url, uint.MaxValue);
  31. uwr.downloadHandler = handler;
  32. yield return uwr.SendWebRequest();
  33. if (!(uwr.isNetworkError || uwr.isHttpError))
  34. {
  35. DownloadFinish(uwr);
  36. }
  37. else
  38. {
  39. DownloadError(uwr);
  40. }
  41. }
  42. }
  43. }

 

9、MonoSingleton

  1. using UnityEngine;
  2. public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
  3. {
  4. private static T instance = null;
  5. private static readonly object locker = new object();
  6. private static bool bAppQuitting;
  7. public static T Instance
  8. {
  9. get
  10. {
  11. if (bAppQuitting)
  12. {
  13. instance = null;
  14. return instance;
  15. }
  16. lock (locker)
  17. {
  18. if (instance == null)
  19. {
  20. instance = FindObjectOfType<T>();
  21. if (FindObjectsOfType<T>().Length > 1)
  22. {
  23. Debug.LogError("不应该存在多个单例!");
  24. return instance;
  25. }
  26. if (instance == null)
  27. {
  28. var singleton = new GameObject();
  29. instance = singleton.AddComponent<T>();
  30. singleton.name = "(singleton)" + typeof(T);
  31. singleton.hideFlags = HideFlags.None;
  32. DontDestroyOnLoad(singleton);
  33. }
  34. else
  35. DontDestroyOnLoad(instance.gameObject);
  36. }
  37. instance.hideFlags = HideFlags.None;
  38. return instance;
  39. }
  40. }
  41. }
  42. private void Awake()
  43. {
  44. bAppQuitting = false;
  45. }
  46. private void OnDestroy()
  47. {
  48. bAppQuitting = true;
  49. }
  50. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/95699
推荐阅读
相关标签
  

闽ICP备14008679号