import { Node, Prefab, instantiate, find } from 'cc'; /** * Toast 管理器 * 单例模式,统一管理 Toast 提示的显示 */ export class ToastManager { private static _instance: ToastManager | null = null; private _prefab: Prefab | null = null; private _container: Node | null = null; static get instance(): ToastManager { if (!this._instance) { this._instance = new ToastManager(); } return this._instance; } private constructor() {} /** * 初始化 Toast 管理器 * @param prefab Toast 预制体 * @param container Toast 容器节点(默认为 Canvas) */ init(prefab: Prefab, container?: Node): void { this._prefab = prefab; this._container = container ?? find('Canvas'); } /** * 显示 Toast 提示 * @param content 提示内容 * @param duration 显示时长(毫秒),默认 2000ms */ show(content: string, duration: number = 2000): void { if (!this._prefab || !this._container) { console.error('[ToastManager] 未初始化,请先调用 init()'); return; } const node = instantiate(this._prefab); this._container.addChild(node); // 动态获取 Toast 组件 const toast = node.getComponent('Toast') as any; if (toast && typeof toast.show === 'function') { toast.show(content, duration); } } /** * 静态快捷方法 */ static show(content: string, duration: number = 2000): void { ToastManager.instance.show(content, duration); } }