ResourceMgr.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { loader, Constructor, resources, Asset } from "cc";
  2. class ResItem {
  3. public url: string;
  4. public isLoading = false;
  5. public callbackArr = [];
  6. }
  7. export class ResourceMgr {
  8. private static _inst: ResourceMgr = null;
  9. public static get inst(): ResourceMgr {
  10. if (!this._inst) {
  11. this._inst = new ResourceMgr();
  12. }
  13. return this._inst;
  14. }
  15. private loadingQueue:[] = [];
  16. public loadRes<T>(url: string, type: any, callback: (err, assets: T) => void) {
  17. let cache = resources.get(url,type) as any;
  18. if(cache){
  19. if(callback){
  20. setTimeout(()=>{
  21. callback(null,cache);
  22. },10);
  23. }
  24. return;
  25. }
  26. let loadingItem:ResItem = this.loadingQueue[url];
  27. if(!loadingItem){
  28. loadingItem = this.loadingQueue[url] = new ResItem();
  29. loadingItem.url = url;
  30. }
  31. loadingItem.callbackArr.push(callback);
  32. if(!loadingItem.isLoading){
  33. loadingItem.isLoading = true;
  34. resources.load(url, type, (err,asset:Asset)=>{
  35. delete this.loadingQueue[url];
  36. for(let k in loadingItem.callbackArr){
  37. let cb = loadingItem.callbackArr[k];
  38. if(cb){
  39. cb(err,asset);
  40. }
  41. }
  42. });
  43. }
  44. }
  45. }