ResourcesMgr.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Asset, AssetManager, log, Prefab, resources, SpriteAtlas, SpriteFrame, TiledMapAsset } from "cc";
  2. class ResourcesMgr{
  3. static instance: ResourcesMgr = null;
  4. private _spriteFrames: Map<string,SpriteFrame> = new Map();
  5. private _prefabs: Map<string, Prefab> = new Map();
  6. private _tmxAsset: Map<string,TiledMapAsset> = new Map();
  7. async loadAllRes(path: string, onProgress:(
  8. (finish: number,total: number, item: AssetManager.RequestItem)=>void) = null){
  9. //下载resources文件夹下的所有资源
  10. //异步函数
  11. const assets: Asset[] = await new Promise<Asset[]>((value, reject)=>{
  12. resources.loadDir(path, onProgress, (err:Error,assets: Asset[])=>{
  13. //完成回调 assets就是那些所有资源的数组
  14. if(err){
  15. reject(err);
  16. }
  17. else{
  18. value(assets);
  19. }
  20. })
  21. })
  22. //遍历所有资源 分门别类存储到对应的容器中
  23. for(const asset of assets){
  24. this.addRes(asset, asset.name);
  25. //console.log(assets)
  26. }
  27. }
  28. async load(path: string, name?: string, atlas: boolean = false){
  29. const asset: Asset = await new Promise((value, reject)=>{
  30. resources.load(path, (err: Error, asset: Asset)=>{
  31. if(err){
  32. reject(err);
  33. }
  34. else{
  35. value(asset);
  36. }
  37. })
  38. });
  39. this.addRes(asset, name, atlas)
  40. }
  41. addRes(asset: Asset, name: string, contactName: boolean = false){
  42. if(asset instanceof SpriteFrame){
  43. this._spriteFrames.set(String(name), asset);
  44. }
  45. else if(asset instanceof Prefab){
  46. this._prefabs.set(String(name), asset);
  47. //console.log(this._prefabs)
  48. }
  49. else if(asset instanceof TiledMapAsset){
  50. this._tmxAsset.set((name), asset)
  51. //console.log(this._tmxAsset)
  52. }
  53. else if(asset instanceof SpriteAtlas){
  54. for(const frame of asset.getSpriteFrames()){
  55. let n: string = frame.name;
  56. if(contactName){
  57. n = name + n;
  58. }
  59. this._spriteFrames.set(n, frame);
  60. }
  61. }
  62. }
  63. getSpriteFrame(name: string): SpriteFrame{
  64. return this._spriteFrames.get(name);
  65. }
  66. getPrefab(name: string): Prefab{
  67. return this._prefabs.get(name);
  68. }
  69. getTmxAsset(name: string): TiledMapAsset{
  70. return this._tmxAsset.get(name);
  71. }
  72. }
  73. export const resMgr: ResourcesMgr = ResourcesMgr.instance = new ResourcesMgr();