Files
engine/docs/zh/core/component.md

4.3 KiB
Raw Blame History

order, title, type, label
order title type label
4 组件 核心 Core

在 Galacean 引擎中,Entity 不具备渲染模型等实际的功能,这些功能是通过加载 Component 组件类来实现的。例如,如果想让一个 Entity 变成一个相机,只需要在该 Entity 上添加相机组件 Camera。这种基于组件的功能扩展方式注重将程序按照功能独立封装,在使用的时候按照需要组合添加,非常有利于降低程序耦合度并提升代码复用率。

常用组件:

名称 描述
Camera 相机
MeshRenderer 静态模型渲染器
SkinnedMeshRenderer 骨骼模型渲染器
Animator 动画控制组件
DirectLight 方向光
PointLight 点光源
SpotLight 聚光灯
ParticleRenderer 粒子系统
BoxCollider 盒碰撞体
SphereCollider 球碰撞体
PlaneCollider 平面碰撞体
Script 脚本

编辑器使用

层级面板 或场景中选择一个实体后,检查器将显示出当前选中节点挂载的所有组件,组件名显示在左上角

Name

你可以在检查器中控制它是否 enabled

Enable

如果不需要它也可以将它删除

Delete

或者编辑它的各种属性

Edit

如果是个空节点,你可以点击 Add Component 按钮来为当前实体添加新的组件。

image-20230926112713126

脚本使用

添加组件

我们使用 addComponent(Component) 添加组件,例如给 Entity  添加“平行光”组件(DirectLight

const lightEntity = rootEntity.createChild("light");
const directLight = lightEntity.addComponent(DirectLight);
directLight.color = new Color(0.3, 0.3, 1);
directLight.intensity = 1;

查找实体上的组件

当我们需要获取某一实体上的组件, getComponent 这个 API 会帮你查找目标组件。

const component = newEntity.getComponent(Animator);

有些时候可能会有多个同一类型的组件,而上面的方法只会返回第一个找到的组件。如果需要找到所有组件可以用 getComponents

const components = [];
newEntity.getComponents(Animator, components);

在 glTF 这种资产得到的实体里,我们可能不知道目标组件位于哪个实体,这时可以使用getComponentsIncludeChildren进行查找。

const components = [];
newEntity.getComponentsIncludeChildren(Animator, components);

获得组件所在的实体

继续开头添加组件的例子。可以直接获得组件所在的实体:

const entity = directLight.entity;

状态

暂时不使用某组件时,可以主动调用组件的 enabled

directLight.enabled = false;