组件
大约 2 分钟基础知识文档组件
组件(Component)用于为实体增加某种特性和功能。例如,可以给一个 Entity 添加一个 DirectionalLight 组件,这样 Entity 就具有了方向光的特性和功能。这种基于组件的功能扩展方式,通过使用组合代替继承,降低程序耦合度提升代码复用率。
提示
Component 作为组件基类,其它类型组件必须继承自 Component 或 Component 的子类。
组件属性
组件方法
_onAwake - 组件唤醒响应,只调用一次,protected方法。
_onEnable - 组件启用响应,可调用多次,protected方法。
_onDisable - 组件禁用响应,可调用多次,protected方法。
_onDestroy - 组件销毁响应,只调用一次,protected方法。
提示
以上四个方法需要由子类根据实际情况选择重载实现。
组件事件
重要
“取消订阅”时如果不指定第二个参数,会取消该类型事件的所有订阅!
- emit - 分发事件。
属性改变事件
Fantasy 3D 内置组件的属性值发生改变时会分发属性改变事件(Attribute_Changed),属性改变事件结构如下所示:
{
type: 'attribute_changed', // 事件类型,始终为'attribute_changed'
name: 'color', // 属性名称
value: '#deacde' // 最新属性值
}
开发人员可以通过监听组件的属性改变事件获知发生改变的属性及最新属性值:
import { EventType } from '@fantasy3d/core';
// 监听组件属性改变事件
component.on( EventType.Attribute_Changed, ( event ) => {
const { name, value } = event;
// 判断‘color’属性是否发生改变
if ( name === 'color' ) {
// TODO:
}
} );
提示
自定义组件可以通过以下方法分发“属性改变事件”:
- 通过属性装饰器(attributeChanged)自动分发:
import { Component, attributeChanged } from '@fantasy3d/core';
class Manual extends Component {
............
// 半径属性
private _radius: number;
/**
* 设置半径
*/
@attributeChanged<number>()
set radius( value: number ) {
this._radius = value;
}
............
}
- 手动分发属性改变事件:
import { Component, EventType } from '@fantasy3d/core';
class Manual extends Component {
............
// 半径属性
private _radius: number;
/**
* 设置半径
*/
set radius( value: number ) {
this._radius = value;
// 分发属性改变事件
this.emit( {
type: EventType.Attribute_Changed,
name: 'radius',
value: value
} );
}
............
}