cocos creator-2.3.4-使用schedule回调函数,实现一个倒计时功能

废话不多说,先上代码:

const {ccclass, property} = cc._decorator;

@ccclass
export default class Countdown extends cc.Component {

    @property(cc.Animation)
    animation: cc.Animation = null;

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

    count: number = 0;
    callback: Function = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {}

    start () {}

    showTime (time: number) {
        this.count = time;
        this.animation.play();

        this.callback = function () {
            if (this.count <= 0) {
                this.labelComponent.unschedule(this.callback);
                return;
            }
            this.count--;
            **this.labelComponent.string = this.count.toString();**  // 访问组件需绑定响应函数调用者为this
        }.bind(this)
        this.labelComponent.schedule(this.callback, 1);
        this.labelComponent.string = this.count.toString();

    }

    // update (dt) {}
}

问题出在这句:this.labelComponent.string = this.count.toString(); ,如果想在this.callback 中设置 this.labelComponent.string,正确的用法是 this.callback = funtion () {}.bind(this),否则会报这样的错误:Uncaught TypeError: Cannot set property 'string' of undefined

creator官方文档-计时器的使用
creator官方文档-bind绑定响应函数的调用者

你可能感兴趣的:(cocos creator-2.3.4-使用schedule回调函数,实现一个倒计时功能)