ConfigLoader.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { JsonAsset, resources } from 'cc';
  2. import { WeaponConfig } from './BulletTypes';
  3. /**
  4. * 轻量配置加载器:管理 weapons.json 数据
  5. * - 可通过 setWeaponsData 直接注入(推荐迁移时使用)
  6. * - 可从 resources 目录加载(路径示例:data/weapons)
  7. */
  8. export class ConfigLoader {
  9. private static weaponsData: { weapons: WeaponConfig[] } | null = null;
  10. public static setWeaponsData(data: { weapons: WeaponConfig[] } | null) {
  11. this.weaponsData = data;
  12. }
  13. public static async loadWeaponsFromResources(path: string): Promise<void> {
  14. return new Promise((resolve, reject) => {
  15. resources.load(path, JsonAsset, (err, asset) => {
  16. if (err) {
  17. reject(err);
  18. return;
  19. }
  20. try {
  21. const json = asset.json as any;
  22. if (!json || !json.weapons) {
  23. throw new Error('Invalid weapons.json structure');
  24. }
  25. this.weaponsData = json as { weapons: WeaponConfig[] };
  26. resolve();
  27. } catch (e) {
  28. reject(e);
  29. }
  30. });
  31. });
  32. }
  33. public static getWeaponConfig(id: string): WeaponConfig | null {
  34. if (!this.weaponsData || !this.weaponsData.weapons) return null;
  35. const w = this.weaponsData.weapons.find(x => x.id === id);
  36. return w ?? null;
  37. }
  38. public static clearCache() {
  39. this.weaponsData = null;
  40. }
  41. }