const { ccclass, property } = cc._decorator;
@ccclass
export default class TimeCounter extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
private elapsedTime: number = 0;
private counting: boolean = false;
start() {
// 在开始时启动计时
this.startTimer();
}
startTimer() {
// 设置计时器为启动状态
this.counting = true;
// 使用schedule函数每秒执行一次updateTimer方法
this.schedule(this.updateTimer, 1, cc.macro.REPEAT_FOREVER, 0);
}
updateTimer(dt: number) {
// 如果计时器处于启动状态,更新已经流逝的时间
if (this.counting) {
this.elapsedTime += dt;
// 在这里可以更新显示计时的文本
this.label.string = this.formatTime(this.elapsedTime);
}
}
stopTimer() {
// 设置计时器为停止状态
this.counting = false;
// 取消schedule
this.unschedule(this.updateTimer);
}
formatTime(seconds: number): string {
// 将秒数格式化为分:秒的形式
const minutes = Math.floor(seconds / 60);
const remainingSeconds = Math.floor(seconds % 60);
return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
}
}
在预制体上挂载这个 label 对应 main 下挂载着一个脚本就可以实现了