squidGame/tgx-games-client/assets/scripts/ScenePreloadManager.ts

113 lines
3.6 KiB
TypeScript
Raw Normal View History

2025-03-23 09:07:30 +08:00
import { _decorator, assetManager, director, Director } from 'cc';
const { ccclass } = _decorator;
/**
*
*
*/
@ccclass('ScenePreloadManager')
export class ScenePreloadManager {
private static _instance: ScenePreloadManager = null;
// 场景预加载映射关系
private readonly scenePreloadMap: Map<string, string[]> = new Map();
// 记录已经预加载的场景
private preloadedScenes: Set<string> = 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();
}
}