美文网首页
CocosCreator中的计时器schedule

CocosCreator中的计时器schedule

作者: 全新的饭 | 来源:发表于2022-10-18 14:01 被阅读0次

官方说明

使用计时器

说明

schedule的3个时间参数

  1. interval:每隔多少秒执行一次
  2. repeat:共执行repeat+1次
  3. delay:调用后,经过多少秒开始执行第一次。若不配置,则默认delay=interval

示例

Test.ts

import { _decorator, Component, Node, Vec3, absMax, Label, input, Input, KeyCode, EventKeyboard, director } from 'cc';
import { Test1 } from './Test1';
const { ccclass, property } = _decorator;

@ccclass('Test')
export class Test extends Component
{
    private _test1: Test1;
    start():void
    { 
        this._test1 = director.getScene().getComponentInChildren(Test1);
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onDestroy(): void
    { 
        this._test1 = null;
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    private onKeyDown(event:EventKeyboard): void
    {
        if (event.keyCode == KeyCode.KEY_A)
        {
            this.myBegin();
        }
        else if (event.keyCode == KeyCode.KEY_D)
        { 
            this.myEnd();
        }
    }

    private myFunc(): void
    {
        this._test1.myFunc();
    } 

    private getCurTime(): string
    { 
        const date = new Date();
        const str = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        return str;
    }

    private myBegin(): void
    { 
        console.info('我的开始!' + this.getCurTime());
        // 1秒后开始执行,共执行2+1=3次,每隔5秒执行1次。
        this.schedule(this.myFunc, 5, 2, 1);
        
    }
    private myEnd(): void
    { 
        console.info('我的结束!' + this.getCurTime());
        // 取消计时器
        this.unschedule(this.myFunc);
    }
}

Tes1.ts

import { _decorator, Component, Node, Vec3, absMax, Label, input, Input, KeyCode, EventKeyboard } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Test1')
export class Test1 extends Component
{

    public myFunc(): void
    {
        console.info("test1当前时间:" + this.getCurTime());
    } 

    private getCurTime(): string
    { 
        const date = new Date();
        const str = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
        return str;
    }
}

相关文章

网友评论

      本文标题:CocosCreator中的计时器schedule

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