UIStateManager.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { _decorator, Component, Node, Button, find } 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/GameSuccess)' })
  14. public successPanel: Node = null;
  15. @property({ type: Node, tooltip: '失败面板 (Canvas/GameDefeat)' })
  16. public defeatPanel: Node = null;
  17. protected init() {
  18. // 自动查找面板
  19. if (!this.successPanel) {
  20. this.successPanel = find('Canvas/GameSuccess');
  21. }
  22. if (!this.defeatPanel) {
  23. this.defeatPanel = find('Canvas/GameDefeat');
  24. }
  25. // 默认隐藏
  26. if (this.successPanel) this.successPanel.active = false;
  27. if (this.defeatPanel) this.defeatPanel.active = false;
  28. // 绑定按钮
  29. this.bindPanelButtons();
  30. // 监听事件
  31. EventBus.getInstance().on(GameEvents.GAME_SUCCESS, this.onGameSuccess, this);
  32. EventBus.getInstance().on(GameEvents.GAME_DEFEAT, this.onGameDefeat, this);
  33. }
  34. private bindPanelButtons() {
  35. this.bindButtonsInPanel(this.successPanel);
  36. this.bindButtonsInPanel(this.defeatPanel);
  37. }
  38. private bindButtonsInPanel(panel: Node) {
  39. if (!panel) return;
  40. const buttons = panel.getComponentsInChildren(Button);
  41. buttons.forEach(btn => {
  42. btn.node.on(Button.EventType.CLICK, () => {
  43. EventBus.getInstance().emit(btn.node.name.toUpperCase() + '_CLICK');
  44. });
  45. });
  46. }
  47. private onGameSuccess() {
  48. if (this.successPanel) this.successPanel.active = true;
  49. }
  50. private onGameDefeat() {
  51. if (this.defeatPanel) this.defeatPanel.active = true;
  52. }
  53. /** 对外接口 */
  54. public closeAllPanels() {
  55. if (this.successPanel) this.successPanel.active = false;
  56. if (this.defeatPanel) this.defeatPanel.active = false;
  57. }
  58. }