如何让Lable中的内容像倒计时一样不断-1

如何让label中的数字不断-1

1赞

在update里面,不断修改Label里面string的值,也可以用tween动画,或者直接循环搞定,再整点插值缓动应该差不多了

    public update(dt: number): void {
        this.unitTime += dt;
        if (this.unitTime < 1) {
            return;
        }
        this.time--;
        this.unitTime--;
        this.label.string = this.time + "";
    }

1赞

我都是用计时器 :rofl:

update(dt: number): void {
        if (this.time <= 0) return;

        this.time -= dt;
        this.timeLab.string = '' + Math.ceil(this.time);
}

谢谢,谢谢,学会了

如果我想在某一时刻暂停,然后又继续,该怎么做呢

public update(dt: number): void {
        if (this.pause) {
            return;        
        }
        this.unitTime += dt;
        if (this.unitTime < 1) {
            return;
        }
        this.time--;
        this.unitTime--;
        this.label.string = this.time + "";
    }
1赞

:smile:膜拜大佬

@property(cc.Label)
label: cc.Label = null;

updateLabel(): void {
    this.label.string = '' + (+this.label.string - 1);
}

start() {
    // 开始不断 -1;
    this.schedule(this.updateLabel, 1); // 1 是间隔时间(秒),调用时并不会立刻-1,而是在间隔时间后才触发第一次-1

    // 某一时刻暂停
    this.unschedule(this.updateLabel);
}

你这样暂停会丢失暂停时那一秒的时间

是的,正在走的周期会被取消,但是我们的效果差不多是一模一样的,this.pause = true;替换成this.unschedule(this.updateLabel);结果是不是一样,咱们的区别就是我这么写不会走太多的 updateLabel,你的会走很多遍 update,还有就是暂停再恢复时,你的会从上次的unitTime剩余时间继续,我的是重新开了一个完整的周期

1、是暂停计时,不是停止计时哦,不应该重新一个周期,而是继续上一个周期。

2、丢失的那一秒其实在表现上还蛮严重的,会出现暂停再恢复大于1秒才走字。

3、update会执行很多次,但是label刷新是1秒一次哦~


那你能帮我看看我这个,如果我想让moods_num<=0的时候结束(停止)计时,然后隐藏背景,该怎么做呢?

// 不建议这里使用匿名函数,不然停止计时只能调用 unscheduleAllCallbacks,
// unscheduleAllCallbacks会把其他别的计时器也给取消,
// 除非你确定 this 对象就只有这一个计时器,并且以后大概率也不会增加
// 否则可能会影响别的代码
this.schedule(() => {
    this.moods_num--;
    this.moods_label.string = `${this.moods_num}`;
    if (this.moods_num <= 0) {
        this.unscheduleAllCallbacks();
        // 隐藏背景
    }
}, interval, repeat, delay);

// 哪怕你把匿名函数临时保存一下也好
let updateLabel = () => {
    this.moods_num--;
    this.moods_label.string = `${this.moods_num}`;
    if (this.moods_num <= 0) {
        this.unschedule(updateLabel);
        // 隐藏背景
    }
}
this.schedule(updateLabel, interval, repeat, delay);