UIStateManager.ts 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // EventBus.getInstance().on(GameEvents.RESET_UI_STATES, this.closeAllPanels, this);
  28. }
  29. private bindPanelButtons() {
  30. this.bindButtonsInPanel(this.endPanel);
  31. }
  32. private bindButtonsInPanel(panel: Node) {
  33. if (!panel) return;
  34. const buttons = panel.getComponentsInChildren(Button);
  35. buttons.forEach(btn => {
  36. btn.node.on(Button.EventType.CLICK, () => {
  37. EventBus.getInstance().emit(btn.node.name.toUpperCase() + '_CLICK');
  38. });
  39. });
  40. }
  41. /**
  42. * 设置游戏结束UI的EndLabel文本
  43. * @param text 要显示的文本 ('SUCCESS' 或 'DEFEAT')
  44. */
  45. private setEndLabelText(text: string) {
  46. if (!this.endPanel) return;
  47. const endLabel = this.endPanel.getChildByPath('Sprite/EndLabel');
  48. if (endLabel) {
  49. const labelComponent = endLabel.getComponent(Label);
  50. if (labelComponent) {
  51. labelComponent.string = text;
  52. console.log(`[UIStateManager] 设置EndLabel文本为: ${text}`);
  53. } else {
  54. console.warn('[UIStateManager] 未找到EndLabel的Label组件');
  55. }
  56. } else {
  57. console.warn('[UIStateManager] 未找到EndLabel节点路径: Sprite/EndLabel');
  58. }
  59. }
  60. private onGameSuccess() {
  61. if (this.endPanel) {
  62. this.endPanel.active = true;
  63. this.setEndLabelText('SUCCESS');
  64. }
  65. }
  66. private onGameDefeat() {
  67. if (this.endPanel) {
  68. this.endPanel.active = true;
  69. this.setEndLabelText('DEFEAT');
  70. }
  71. }
  72. /** 对外接口 */
  73. public closeAllPanels() {
  74. if (this.endPanel) this.endPanel.active = false;
  75. }
  76. }