UIStateManager.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { _decorator, Component, Node, Button, find, Label } from 'cc';
  2. import { BaseSingleton } from '../Core/BaseSingleton';
  3. import EventBus, { GameEvents } from '../Core/EventBus';
  4. const { ccclass, property } = _decorator;
  5. /**
  6. * UIStateManager
  7. * 负责游戏内 UI 面板的显示/隐藏,以及按钮事件分发。
  8. * 注意:仅处理 Canvas/GameLevelUI 下与战斗胜败相关的 UI。
  9. */
  10. @ccclass('UIStateManager')
  11. export class UIStateManager extends BaseSingleton {
  12. public static _instance: UIStateManager;
  13. @property({ type: Node, tooltip: '游戏结束面板 (Canvas/GameEnd)' })
  14. public endPanel: Node = null;
  15. protected init() {
  16. // 自动查找面板
  17. if (!this.endPanel) {
  18. this.endPanel = find('Canvas/GameEnd');
  19. }
  20. // 默认隐藏
  21. if (this.endPanel) this.endPanel.active = false;
  22. // 绑定按钮
  23. this.bindPanelButtons();
  24. // 监听事件
  25. EventBus.getInstance().on(GameEvents.GAME_SUCCESS, this.onGameSuccess, this);
  26. EventBus.getInstance().on(GameEvents.GAME_DEFEAT, this.onGameDefeat, this);
  27. }
  28. private bindPanelButtons() {
  29. this.bindButtonsInPanel(this.endPanel);
  30. }
  31. private bindButtonsInPanel(panel: Node) {
  32. if (!panel) return;
  33. const buttons = panel.getComponentsInChildren(Button);
  34. buttons.forEach(btn => {
  35. btn.node.on(Button.EventType.CLICK, () => {
  36. EventBus.getInstance().emit(btn.node.name.toUpperCase() + '_CLICK');
  37. });
  38. });
  39. }
  40. /**
  41. * 设置游戏结束UI的EndLabel文本
  42. * @param text 要显示的文本 ('SUCCESS' 或 'DEFEAT')
  43. */
  44. private setEndLabelText(text: string) {
  45. if (!this.endPanel) return;
  46. const endLabel = this.endPanel.getChildByPath('Sprite/EndLabel');
  47. if (endLabel) {
  48. const labelComponent = endLabel.getComponent(Label);
  49. if (labelComponent) {
  50. labelComponent.string = text;
  51. console.log(`[UIStateManager] 设置EndLabel文本为: ${text}`);
  52. } else {
  53. console.warn('[UIStateManager] 未找到EndLabel的Label组件');
  54. }
  55. } else {
  56. console.warn('[UIStateManager] 未找到EndLabel节点路径: Sprite/EndLabel');
  57. }
  58. }
  59. private onGameSuccess() {
  60. if (this.endPanel) {
  61. this.endPanel.active = true;
  62. this.setEndLabelText('SUCCESS');
  63. }
  64. }
  65. private onGameDefeat() {
  66. if (this.endPanel) {
  67. this.endPanel.active = true;
  68. this.setEndLabelText('DEFEAT');
  69. }
  70. }
  71. /** 对外接口 */
  72. public closeAllPanels() {
  73. if (this.endPanel) this.endPanel.active = false;
  74. }
  75. }