import { _decorator, assetManager, director, Director } from 'cc'; const { ccclass } = _decorator; /** * 场景预加载管理器 * 用于在当前场景加载后预加载下一个场景的资源 */ @ccclass('ScenePreloadManager') export class ScenePreloadManager { private static _instance: ScenePreloadManager = null; // 场景预加载映射关系 private readonly scenePreloadMap: Map = new Map(); // 记录已经预加载的场景 private preloadedScenes: Set = new Set(); // 是否正在预加载 private isPreloading: boolean = false; public static get instance(): ScenePreloadManager { if (!this._instance) { this._instance = new ScenePreloadManager(); this._instance.initialize(); } return this._instance; } private initialize(): void { // 设置预加载映射关系 - 使用简单的场景名称 this.scenePreloadMap.set('lobby_arean', ['WoodenManScene']); // 大厅 -> 木头人 this.scenePreloadMap.set('WoodenManScene', ['level2Scene']); // 木头人 -> 拔河 this.scenePreloadMap.set('level2Scene', ['BallScene']); // 拔河 -> 弹珠 // 监听场景加载完成事件 director.on(Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLoaded, this); } /** * 场景加载完成回调 */ private onSceneLoaded(): void { // 获取当前场景名称 const currentScene = director.getScene()?.name || ''; console.log(`当前场景: ${currentScene}`); // 尝试预加载下一个场景 this.preloadNextScenes(currentScene); } /** * 预加载下一个场景 * @param currentScene 当前场景名称 */ private preloadNextScenes(currentScene: string): void { if (this.isPreloading || !currentScene) return; // 获取下一个需要预加载的场景列表 const nextScenes = this.scenePreloadMap.get(currentScene); if (!nextScenes || nextScenes.length === 0) return; this.isPreloading = true; // 延迟1秒进行预加载,避免影响当前场景加载 setTimeout(() => { for (const nextScene of nextScenes) { // 如果已经预加载过,则跳过 if (this.preloadedScenes.has(nextScene)) continue; console.log(`预加载场景: ${nextScene}`); this.preloadScene(nextScene); } this.isPreloading = false; }, 1000); } /** * 预加载指定场景 * @param sceneName 场景名称 */ private preloadScene(sceneName: string): void { try { // 简单直接地使用director预加载场景 director.preloadScene(sceneName, (err) => { if (err) { console.error(`预加载场景失败: ${sceneName}`, err); return; } console.log(`预加载场景成功: ${sceneName}`); this.preloadedScenes.add(sceneName); }); } catch (error) { console.error(`预加载场景出错: ${sceneName}`, error); } } /** * 手动预加载指定场景 * @param sceneName 场景名称 */ public preloadSceneManually(sceneName: string): void { if (this.preloadedScenes.has(sceneName)) return; this.preloadScene(sceneName); } /** * 清除预加载的场景缓存 */ public clearPreloadCache(): void { this.preloadedScenes.clear(); } }