ResourcesMgr.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  26. }
  27. async load(path: string, name?: string, atlas: boolean = true){
  28. const asset: Asset = await new Promise((value, reject)=>{
  29. resources.load(path, (err: Error, asset: Asset)=>{
  30. if(err){
  31. reject(err);
  32. }
  33. else{
  34. value(asset);
  35. }
  36. })
  37. });
  38. this.addRes(asset, name, atlas)
  39. }
  40. addRes(asset: Asset, name: string, atlas: boolean = true){
  41. if(asset instanceof SpriteFrame){
  42. this._spriteFrames.set(String(name), asset);
  43. }
  44. if(asset instanceof Prefab){
  45. this._prefabs.set(String(name), asset);
  46. //console.log(this._prefabs)
  47. }
  48. if(asset instanceof TiledMapAsset){
  49. this._tmxAsset.set((name), asset)
  50. }
  51. if(asset instanceof SpriteAtlas){
  52. if(atlas){
  53. for(const frame of asset.getSpriteFrames()){
  54. this._spriteFrames.set(name + frame.name, frame);
  55. }
  56. }
  57. }
  58. }
  59. getSpriteFrame(name: string): SpriteFrame{
  60. return this._spriteFrames.get(name);
  61. }
  62. getPrefab(name: string): Prefab{
  63. return this._prefabs.get(name);
  64. }
  65. getTmxAsset(name: string): TiledMapAsset{
  66. return this._tmxAsset.get(name);
  67. }
  68. }
  69. export const resMgr: ResourcesMgr = ResourcesMgr.instance = new ResourcesMgr();