// TopBarController.ts import { _decorator, Component, Node, Button, Label, find } from 'cc'; import { SaveDataManager } from '../LevelSystem/SaveDataManager'; const { ccclass, property } = _decorator; @ccclass('TopBarController') export class TopBarController extends Component { /* 顶部资源 & 关卡 */ @property(Node) moneyAddBtn: Node = null; // 绿色 + @property(Node) diamondAddBtn: Node = null; // 紫色 + @property(Node) moneyLabel: Node = null; // 金币数字 @property(Node) diamondLabel: Node = null; // 钻石数字 private sdm: SaveDataManager = null; onLoad() { this.sdm = SaveDataManager.getInstance(); this.bindButtons(); this.refreshAll(); } /* 绑定按钮事件 */ private bindButtons() { this.moneyAddBtn?.on(Button.EventType.CLICK, () => this.addCoins(100), this); this.diamondAddBtn?.on(Button.EventType.CLICK, () => this.addDiamonds(20), this); } /* ================= 业务逻辑 ================= */ private addCoins(v: number) { this.sdm.addCoins(v, 'ad'); this.refreshCurrency(); } private addDiamonds(v: number) { this.sdm.addDiamonds(v, 'ad'); this.refreshCurrency(); } /* ================= 刷新 ================= */ private refreshCurrency() { const mLbl = this.moneyLabel?.getComponent(Label) || this.moneyLabel as unknown as Label; if (mLbl) mLbl.string = this.format(this.sdm.getCoins()); const dLbl = this.diamondLabel?.getComponent(Label) || this.diamondLabel as unknown as Label; if (dLbl) dLbl.string = this.format(this.sdm.getDiamonds()); } private refreshAll() { this.refreshCurrency(); } // 供外部调用的公共刷新接口 public updateUI(): void { this.refreshAll(); } // 供其他控制器调用的静态更新方法 public static updateTopBarUI(): void { const topBarNode = find('Canvas/TopBar'); const topBarController = topBarNode?.getComponent('TopBarController'); if (topBarController && 'updateUI' in topBarController) { (topBarController as any).updateUI(); } } /* =============== Util =============== */ private format(n: number) { return n >= 1000000 ? (n / 1e6).toFixed(1) + 'M' : n >= 1000 ? (n / 1e3).toFixed(1) + 'K' : n.toString(); } }