lawless/client/assets/scripts/core/GameManager.ts

75 行
2.0 KiB
TypeScript

import { _decorator, Component, director, game } from 'cc';
import { NetworkManager } from './NetworkManager';
import { ConfigManager } from './ConfigManager';
const { ccclass, property } = _decorator;
/**
* GameManager 全局单例
* 负责场景切换、全局状态持有、核心管理器初始化。
*/
@ccclass('GameManager')
export class GameManager extends Component {
private static _instance: GameManager | null = null;
public static getInstance(): GameManager {
if (!GameManager._instance) {
// 运行时将由 LoginScene 挂载的节点负责创建
console.warn('GameManager not mounted yet');
}
return GameManager._instance!;
}
@property({ type: NetworkManager })
public networkManager: NetworkManager | null = null;
@property({ type: ConfigManager })
public configManager: ConfigManager | null = null;
public playerId: string = '';
public characterId: string = '';
public nakamaToken: string = '';
onLoad() {
if (GameManager._instance === null) {
GameManager._instance = this;
game.addPersistRootNode(this.node);
} else {
this.destroy();
return;
}
this.networkManager = this.networkManager ?? this.getComponent(NetworkManager);
this.configManager = this.configManager ?? this.getComponent(ConfigManager);
}
/**
* 切换场景
*/
public switchScene(sceneName: string): void {
director.loadScene(sceneName);
}
/**
* 登录后设置身份凭证
*/
public setAuth(playerId: string, characterId: string, token: string): void {
this.playerId = playerId;
this.characterId = characterId;
this.nakamaToken = token;
}
/**
* 获取当前角色 ID
*/
public getCharacterId(): string {
return this.characterId;
}
onDestroy() {
if (GameManager._instance === this) {
GameManager._instance = null;
}
}
}