> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/custom-components.md).

# 自定义组件

创建一个自定义组件来处理与实体相关的特定数据

实体的数据存储在其 [组件](/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md)中。Decentraland SDK 提供了一系列基础组件，用于管理实体的不同方面，例如位置、形状、材质等。引擎知道如何解读这些组件中的信息，并会在组件的值发生变化时相应地更改实体的渲染效果。

如果场景逻辑需要存储有关实体的信息，而 SDK 的默认组件无法处理这些信息，你可以在场景中创建自定义组件类型。然后，你可以构建 [系统](/creator/content-creator-zh/chang-jing-sdk7/jia-gou/systems.md) 来检查这些组件是否发生变化，并作出相应响应。

## 定义组件

要定义新组件，请使用 `engine.defineComponent`。每个组件都需要以下内容：

* 一个 **componentName**：一个唯一的字符串标识符，SDK 在内部用它来识别此组件类型。只要确保唯一，可以使用任意字符串。
* 一个 **schema**：用于定义组件所持有数据结构的类。
* **默认值** *（可选）*：一个包含默认值的对象；未提供值时，将使用这些默认值初始化组件副本。

```ts
export const WheelSpinComponent = engine.defineComponent('wheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})
```

{% hint style="warning" %}
**📔 注意**：自定义组件必须在 `main()` 函数之外编写，并放在单独的文件中。它们需要在 `main()` 执行之前先被解析。建议将它们放在 `/components` 文件夹中，该文件夹位于 `/src`目录内，每个组件各自存放在一个文件中。这样更便于在未来的项目中重复使用。
{% endhint %}

定义自定义组件后，你可以创建该组件的实例，并将它们关联到场景中的实体。创建组件实例时，需要为组件架构中的每个字段提供值。这些值必须符合各字段声明的类型。

```ts
// 创建实体
const wheel1 = engine.addEntity()
const wheel2 = engine.addEntity()

// 创建组件实例
WheelSpinComponent.create(wheel1, {
	spinning: true,
	speed: 10,
})

WheelSpinComponent.create(wheel2, {
	spinning: false,
	speed: 0,
})
```

为实体添加组件时，会为该实体创建一个新的组件副本，其中保存着该实体的专属数据。

自定义组件还可以实现其他组件常见的功能：

```ts
// 从实体获取组件的只读实例
const readOnlyInstance = MyCustomComponent.get(myEntity)

// 从实体获取组件的可变实例
const mutableInstance = MyCustomComponent.getMutable(myEntity)

// 删除实体上的组件实例
MyCustomComponent.deleteFrom(myEntity)
```

## 关于 componentName

每个组件都必须有一个唯一的组件名称或标识符，以便在内部区分。你不需要在代码的其他地方使用这个内部标识符。一个好做法是使用分配给组件的相同名称，但首字母改为小写；不过，最重要的是确保该标识符在项目中唯一。

创建要作为库的一部分共享的组件时，请注意，库中的组件名称不得与使用该库的项目中的任何组件名称重复，也不得与该项目使用的其他库中的组件名称重复。为避免名称冲突，建议将库名称作为 `componentName` 字符串的一部分。可以采用以下格式： `${packageName}::${componentName}`。例如，如果你构建了一个`MyUtilities` 库，其中包含一个 `MoveEntity` 组件，请将该组件的 `componentName` 设置为 `MyUtilities::moveEntity`.

## 作为标记的组件

你可能希望添加一个组件，仅用于标记实体以便与其他实体区分开来，而不存储任何数据。要实现这一点，请将架构留为空对象。

在使用 [组件查询](/creator/content-creator-zh/chang-jing-sdk7/jia-gou/querying-components.md)时，这尤其有用。简单的标记组件可以用来区分实体，并避免系统遍历超出所需数量的实体。

```ts
export const IsEnemyFlag = engine.defineComponent('isEnemyFlag', {})
```

然后，你可以创建一个系统，遍历所有包含此组件的实体。

```ts
export function handleEnemies() {
	for (const [entity] of engine.getEntitiesWith(IsEnemyFlag)) {
		// 对每个实体执行某项操作
	}
}

engine.addSystem(handleEnemies)
```

## 组件架构

架构描述组件内数据的结构。组件可以存储任意数量的字段，每个字段都必须包含在架构结构中。架构可以根据需要包含任意层级的嵌套项。

架构中的每个字段都必须声明类型。只能使用 SDK 提供的特殊架构类型。例如，使用类型 `Schemas.Boolean` 而不是类型 `boolean`。输入 `Schemas.` 你的 IDE 就会显示所有可用选项。

```ts
export const WheelSpinComponent = engine.defineComponent('WheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})
```

上面的示例定义了一个组件，其架构包含两个值：一个 `spinning` 布尔值和一个 `speed` 浮点数。

你可以在定义组件时直接编写架构，也可以为了提高可读性，先创建架构，再引用它。

```ts
// 选项 1：内联定义
export const WheelSpinComponent = engine.defineComponent('WheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})

// 选项 2：分别定义架构和组件

//// 架构
const mySchema = {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
}

//// 组件
export const WheelSpinComponent = engine.defineComponent(
	'WheelSpinComponent',
	mySchema
)
```

{% hint style="info" %}
**💡 提示**：创建组件实例时，按下 *Ctrl + Space*.
{% endhint %}

### 默认架构类型

以下基本类型可用于架构的字段中：

* `Schemas.Boolean`
* `Schemas.Byte`
* `Schemas.Double`
* `Schemas.Float`
* `Schemas.Int`
* `Schemas.Int64`
* `Schemas.Number`
* `Schemas.Short`
* `Schemas.String`
* `Schemas.Entity`

此外还有以下复杂类型。每种类型都包含一系列嵌套属性，且属性值为数值。

* `Schemas.Vector3`
* `Schemas.Quaternion`
* `Schemas.Color3`
* `Schemas.Color4`

{% hint style="info" %}
**💡 提示**：请参阅 [几何类型](/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/special-types.md) 和 [颜色类型](/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md) ，详细了解这些数据类型的用途。
{% endhint %}

例如，你可以在组件中使用这些架构类型来追踪实体的逐步移动。此组件将初始位置和最终位置存储为 Vector3 值，并将速度和已完成路径的比例存储为浮点数。完整示例请参阅 [移动实体](/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/move-entities.md#move-between-two-points) 。

```ts
const MoveTransportData = {
	start: Schemas.Vector3,
	end: Schemas.Vector3,
	fraction: Schemas.Float,
	speed: Schemas.Float,
}

export const LerpTransformComponent = engine.defineComponent(
	'LerpTransformComponent',
	MoveTransportData
)
```

### 数组类型

若要将字段类型设为数组，请使用 `Schemas.Array()`。将数组元素的类型作为参数传入。

```ts
const MySchema = {
	numberList: Schemas.Array(Schemas.Int),
}
```

使用 `MyComponent.get()`读取数组字段时，返回的数组为只读。无法使用会原地修改数组的方法，例如 `.push()`。需要修改数组内容时，请使用 `MyComponent.getMutable()` 。

### 可选字段

使用 `Schemas.Optional()` 可让字段存储一个值或 `undefined`.

```ts
const MySchema = {
	playerId: Schemas.Optional(Schemas.String),
	score: Schemas.Optional(Schemas.Int),
}
```

只有 `undefined` 才表示“未设置”。像 `false`, `0`和 `''` 这样的假值也会按原样存储和读取。

### 嵌套架构类型

要将字段类型设为对象，请使用 `Schemas.Map()`。将此对象的内容作为属性传入。这个嵌套对象本质上也是一个架构，嵌套在父架构中。

```ts
const MySchema = {
	simpleField: Schemas.Boolean,
	myComplexField: Schemas.Map({
		nestedField1: Schemas.Boolean,
		nestedField2: Schemas.Boolean,
	}),
}
```

或者，为了让代码更易读、更易复用，你可以单独定义嵌套架构，然后在定义父架构时引用它，从而实现相同的效果。

```ts
const MyNestedSchema = Schemas.Map({
	nestedField1: Schemas.Boolean,
	nestedField2: Schemas.Boolean,
})

const MySchema = {
	simpleField: Schemas.Boolean,
	myComplexField: MyNestedSchema,
}
```

### 枚举类型

你可以将架构中字段的类型设为枚举。枚举可用于从有限数量的选项中轻松选择，并为每个选项提供易于理解的值。

要将字段类型设为枚举，必须先定义枚举。然后，你可以使用以下方式引用它： `Schemas.EnumNumber` 或 `Schemas.EnumString`具体取决于枚举的类型。这些函数接受两个参数：要引用的枚举，以及用于此字段的默认值。

```ts
//// 字符串枚举

// 定义枚举
enum Color {
	Red = 'red',
	Green = 'green',
	Pink = 'pink',
}

// 定义一个在字段中使用此枚举的组件
const ColorComponent = engine.defineComponent('Color', {
	color: Schemas.EnumString<Color>(Color, Color.Red),
})

// 在实体上使用组件
ColorComponent.create(engine.addEntity(), { color: Color.Green })

//// 数字枚举

// 定义枚举
enum CurveType {
	LINEAR,
	EASEIN,
	EASEOUT,
}

// 定义一个在字段中使用此枚举的组件
const CurveComponent = engine.defineComponent('curveComponent', {
	curve: Schemas.EnumNumber<CurveType>(CurveType, CurveType.LINEAR),
})

// 在实体上使用组件
CurveComponent.create(engine.addEntity(), { curve: CurveType.EASEIN })
```

### 可互换类型

你可以将架构中字段的类型设为遵循 `oneOf` 模式，从而接受不同的类型。

```ts
const MySchema = {
	myField: Schemas.OneOf({ type1: Schemas.Vector3, type2: Schemas.Quaternion }),
}

export const MyComponent = engine.defineComponent('MyComponent', MySchema)
```

创建组件实例时，需要使用 `$case`指定所选类型，例如：

```ts
MyComponent.create(myEntity, {
	myField: {
		$case: 'type1',
		value: Vector3.create(1, 1, 1),
	},
})
```

将此字段留空也是有效的。未设置的 `OneOf` 字段没有 `$case` ，读取时会得到一个空对象， `{}`.

### 单一类型的组件

组件不一定要包含由多个字段组成的对象。若要定义一个只存储单个值的组件，请使用 `engine.defineComponentFromSchema()` 并直接传入类型：

```ts
// 每个实体包含一个数字的组件
export const Score = engine.defineComponentFromSchema('my-scene::Score', Schemas.Int)

// 每个实体包含一个数字列表的组件
export const History = engine.defineComponentFromSchema(
	'my-scene::History',
	Schemas.Array(Schemas.Int)
)
```

这些组件的行为与其他组件相同，包括存储的值为假值时也是如此。值为 `Score` 的 `0` 是一个已存在且持有 `0`的组件，而不是缺失的组件。

## 默认值

为组件设置默认值通常很有用，这样每次创建新副本时就不必显式设置每个值。

这个 `engine.defineComponent()` 函数接受第三个参数，可用于传入一个包含默认值的对象。此对象可以包含架构中的部分或全部值。对于默认值和初始化组件副本时提供的值都未指定的字段，会将其初始化为类似零值的值，例如 `0`, `false`或空字符串，具体取决于类型。

```ts
// 定义

//// 架构
const mySchema = {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
}

//// 默认值
const myDefaultValues = {
	spinning: true,
	speed: 1,
}

//// 组件
export const WheelSpinComponent = engine.defineComponent(
	'WheelSpinComponent',
	mySchema,
	myDefaultValues
)

// 用法
export function main() {
	//// 创建实体
	const wheel = engine.addEntity()
	const wheel2 = engine.addEntity()

	//// 使用默认值初始化组件
	WheelSpinComponent.create(wheel)

	//// 使用一个自定义值初始化组件，其余值使用默认值
	WheelSpinComponent.create(wheel2, { speed: 5 })
}
```

上面的示例创建了一个 `WheelSpinComponent` 组件，其中包含架构和一组默认值。之后，如果初始化此组件的副本时未指定任何值，就会使用这些默认值。

## 订阅变更

一种常见用法是仅在某个组件中的数据发生变化时运行函数。使用 [OnChange](/creator/content-creator-zh/chang-jing-sdk7/jia-gou/subscribe-to-changes.md) 函数即可避免定义系统，也无需显式比较新旧值。

```ts
export function main() {
	//创建实体等

	WheelSpinComponent.onChange(myEntity, (componentData) => {
		if (!componentData) return
		console.log(componentData.speed)
		console.log(componentData.spinning)
	})
}
```

## 构建使用组件的系统

定义组件并将其添加到场景中的实体后，就可以创建 [系统](/creator/content-creator-zh/chang-jing-sdk7/jia-gou/systems.md) 以执行逻辑，并利用存储在组件中的这些数据。

```ts
// 定义组件
export const WheelSpinComponent = engine.defineComponent('WheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})

// 用法
export function main() {
	// 创建实体
	const wheel1 = engine.addEntity()
	const wheel2 = engine.addEntity()

	// 创建组件实例
	WheelSpinComponent.create(wheel1, {
		spinning: true,
		speed: 10,
	})

	WheelSpinComponent.create(wheel2, {
		spinning: false,
		speed: 0,
	})
}

// 定义一个系统来遍历这些实体
export function spinSystem(dt: number) {
	// 遍历所有带有 WheelSpinComponent 的实体
	for (const [entity, wheelSpin] of engine.getEntitiesWith(
		WheelSpinComponent
	)) {
		// 仅当 spinning == true 时执行操作
		if (wheelSpin.spinning) {
			// fetch a mutable Transform component
			const transform = Transform.getMutable(entity)

			// 相应地更新旋转值
			transform.rotation = Quaternion.multiply(
				transform.rotation,
				Quaternion.fromAngleAxis(dt * wheelSpin.speed, Vector3.Up())
			)
		}
	}
}

// 将系统添加到引擎
engine.addSystem(spinSystem)
```

上面的示例定义了一个系统，用于遍历所有包含自定义 `wheelSpinComponent`的实体，并在游戏循环的每个时刻使它们稍微旋转。旋转幅度与每个实体组件实例中存储的 `speed` 值成正比。该示例使用 [组件查询](/creator/content-creator-zh/chang-jing-sdk7/jia-gou/querying-components.md) 来仅获取相关实体。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/custom-components.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
