美文网首页
Cocos 3.x 计时器

Cocos 3.x 计时器

作者: 合肥黑 | 来源:发表于2021-05-19 09:32 被阅读0次

参考使用计时器

在 Cocos Creator 3.0 中,我们为组件提供了方便的计时器。也许有人会认为 setTimeout 和 setInterval 就足够了,开发者当然可以使用这两个函数,不过我们更推荐使用计时器,因为它更加强大灵活,和组件也结合得更好!

下面是 Component 中所有关于计时器的函数:

  • schedule:开始一个计时器
  • scheduleOnce:开始一个只执行一次的计时器
  • unschedule:取消一个计时器
  • unscheduleAllCallbacks:取消这个组件的所有计时器
一、传递参数
1.匿名函数
this.scheduleOnce(function(){
this.spawnFoe(spawn)
}, spawn.outTime);
2.更常用的是bind方式
    private showCombineEffect(pos: Vec3) {
        let effect = PoolManager.Instance.getNode(this.combineEffect, this.combineEffectParent);
        effect.setPosition(new Vec3(pos.x, pos.y, pos.z + 3));
        //播放完后回收
        this.scheduleOnce(this.poolCombineEffect.bind(this, effect), 1.5);
    }

    private poolCombineEffect(n: Node) {
        PoolManager.Instance.putNode(n);
    }

scheduleOnce除了用bind传参,还有其它方法传参数吗?中作者提出,bind会创建一个新函数,会导致unschedule无效。所以可以这样干:

test(p: number) {
    console.log("test:", p);
}
private _testFunc: any;


start() {
    this._testFunc = this.test.bind(this, 22);
    this.scheduleOnce(this._testFunc, 5);
}

onClickBackHome() {
    this.unschedule(this._testFunc);
}

相关文章

网友评论

      本文标题:Cocos 3.x 计时器

      本文链接:https://www.haomeiwen.com/subject/pcdllltx.html