类似于c#中的event功能。
假设:血量条需要关注血量的变化
组件HpCtr中持有一个字段hp,通过该组件提供的方法setHp可以修改hp值。
public static readonly MinHp: number = 0;
public static readonly MaxHp: number = 100;
private _hp: number;
public get hp(): number { return this._hp; }
private setHp(v: number): void
{
...
}
期望当hp值被修改时,发出事件告知外界。
发出事件
- 在组件HpCtr中声明一个字段eventTarget:EventTarget,提供getter供外界访问。
private _eventTarget: EventTarget;
public get eventTarget(): EventTarget { return this._eventTarget };
- 创建一个常量作为血量变化事件的标识名。
public static readonly ChangeHpEvent: string = 'HpCtrChangeHpEvent';
- 在setHp方法中,触发该事件。
this.eventTarget.emit(HpCtr.ChangeHpEvent, this._hp);
接收事件
组件HpBar需关注血量变化。
- 在该组件初始化时,关注血量变化事件;在该组件销毁时,取消关注。
private init(hpCtr:HpCtr): void
{
this._hpCtr = hpCtr;
this._hpCtr.eventTarget.on(HpCtr.ChangeHpEvent, this.onHpChanged, this);
}
private myDestroy(): void
{
if (this._hpCtr != null)
{
this._hpCtr.eventTarget.off(HpCtr.ChangeHpEvent, this.onHpChanged, this);
this._hpCtr = null;
}
}
private onHpChanged(hp: number)
{
...
}
额外知识
1. 获取本场景中的“单例”组件时,可通过如下方式。(如获取LevelSys)
levelSys:LevelSys = director.getScene().getComponentInChildren(LevelSys);
2 创建自己的代码模板
在Assets窗口点鼠标右键
image.png
在打开的目录下创建名称无后缀的模板文件,如“FanCustomComponent”
image.png
我创建的代码模板文件内容如下:增加了初始化和销毁的方法。
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('<%UnderscoreCaseClassName%>')
export class <%UnderscoreCaseClassName%> extends Component
{
start()
{
this.init();
}
onDestroy()
{
this.myDestroy();
}
update(deltaTime: number)
{
}
private init(): void
{
}
private myDestroy(): void
{
}
}
/**
* COMMENTS_GENERATE_IGNORE
* Use "COMMENTS_GENERATE_IGNORE" tag if you do not want later created scripts to contain these comments.
*
* Predefined Variables
* You can use predefined variables below to setup your scripting preference. For example, whether to use camel case style.
*
* <%UnderscoreCaseClassName%>, class name in underscore format, like 'new_component'
* <%CamelCaseClassName%>, class name in camel format, like 'NewComponent'
* <%Author%>, Who create this file
* <%DateTime%>, when create this file
* <%FileBasename%>, creating file name with extension
* <%FileBasenameNoExtension%>, creating file name without extension
* <%URL%>, url of this file in COCOS ASSET URL format
* <%ManualUrl%>, url of office help document, like 'https://docs.cocos.com/creator/manual/en/'
*
*
* Example:
*
@ccclass('<%UnderscoreCaseClassName%>')
export class <%UnderscoreCaseClassName%> extends Component {
// class member could be defined like this.
dummy = '';
// Use 'property' decorator if your want the member to be serializable.
@property
serializableDummy = 0;
start () {
// Your initialization goes here.
}
update (deltaTime: number) {
// Your update function goes here.
}
}
*
* Learn more about scripting: <%ManualUrl%>scripting/
* Learn more about CCClass: <%ManualUrl%>scripting/decorator.html
* Learn more about life-cycle callbacks: <%ManualUrl%>scripting/life-cycle-callbacks.html
*/
网友评论