> 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/composites.md).

# 组合文件

在运行时从组合文件生成一棵实体和组件树

一个 *复合体* 是一个用于描述 [实体和组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md)树状结构的文件。无需编写代码逐个创建实体，你可以将该结构存储在复合体文件中，然后通过一次调用生成整个结构。

你可能已经在使用复合体，只是没有意识到：

* 每个场景都有一个 `main.composite` 文件，其中保存了你在 [场景编辑器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/ru-men/about-editor.md)中通过可视化方式添加和配置的所有内容。场景启动时会自动加载此文件。
* [自定义项目](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/custom-items.md) 保存为 `composite.json` 文件。每个自定义项目都是一个复合体，可在多个场景中重复使用。

本页介绍如何在运行时通过代码生成复合体，例如在场景逻辑中动态生成自定义项目。

## 生成复合体

生成复合体分为两步： **加载** 复合体文件，然后 **生成** 复合体。加载是异步的，生成是同步的，因此始终应先加载、再生成：

```ts
import { engine, Composite, getCompositeProvider } from "@dcl/sdk/ecs";

export async function spawnBarrel() {
  const src = "barrel.composite";
  const provider = getCompositeProvider();
  if (!provider || !provider.loadComposite) return;

  // 1. 从文件加载复合体
  const resource = await provider.loadComposite(src);

  // 2. 生成复合体：创建其中的所有实体和组件
  const barrel = Composite.instance(engine, resource, provider);
  return barrel;
}
```

`provider.loadComposite(src)` 会读取复合体文件并将其加载到内存中。在使用 `@dcl/sdk`构建的常规场景中，复合体提供程序已为你配置好，你可以通过 `getCompositeProvider()` 函数获取它，该函数来自 `@dcl/sdk/ecs`.

`Composite.instance()` 随后会创建复合体中描述的所有实体及其组件，并返回生成树的 **根实体** 。使用返回的实体可以在之后读取或修改组件，例如重新定位或移除生成的项目。

{% hint style="info" %}
**💡 提示**：如果不想编写代码，也可以在场景编辑器中使用 **生成实体** 操作。请参阅 [关于生成实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/smart-items-advanced.md#about-spawning-entities).
{% endhint %}

{% hint style="warning" %}
**📔 注意**：必须先加载复合体，才能生成它。 `Composite.instance()` 是同步的，只能生成已加载到内存中的复合体。只有 `main.composite` 会随场景一起打包并从一开始就可用；其他复合体文件都必须先通过 `loadComposite()` 加载。若要同步检查复合体是否已可用，请使用 `provider.getCompositeOrNull(src)`.

`loadComposite()` 具有幂等性：它会根据复合体的 `src` 字符串来识别复合体，因此使用相同路径再次调用时不会重新加载文件，而是返回已加载的复合体。你可以在每次生成前安全地调用它，无需担心重复加载同一文件。
{% endhint %}

### 生成到现有实体上

默认情况下， `Composite.instance()` 会创建一个新实体来容纳生成的树。若要生成到已有实体上，请在选项中传入 `rootEntity` ：

```ts
// 直接在场景根节点生成复合体，不创建包装实体
const barrel = Composite.instance(engine, resource, provider, {
  rootEntity: engine.RootEntity,
})
```

## 设置生成的复合体的位置

若要将生成的复合体放置在特定位置、设置旋转或缩放，请在 `Transform` 组件中设置由 `Composite.instance()`.

```ts
import { engine, Composite, getCompositeProvider, Transform } from "@dcl/sdk/ecs";
import { Vector3 } from "@dcl/sdk/math";

export async function spawnBarrel() {
  const src = "barrel.composite";
  const provider = getCompositeProvider();
  if (!provider || !provider.loadComposite) return;

  const resource = await provider.loadComposite(src);

  // 在指定位置生成复合体
  const barrel = Composite.instance(engine, resource, provider);
  Transform.createOrReplace(barrel, {
    position: Vector3.create(8, 0, 8),
  });
}
```

{% hint style="warning" %}
**📔 注意**: `Transform.createOrReplace()` 会替换根实体已有的 Transform 组件。只有根实体会受影响；子实体的位置仍保持相对于根实体不变。
{% endhint %}

## 当前限制：嵌套复合体

生成适用于自包含复合体和自定义物品。复合体可以在其中一个实体上引用另一个复合体，但 `loadComposite()` 不会 **递归** 加载这些嵌套引用：它只会加载你传入的文件。

生成时， `Composite.instance()` 会递归处理已加载到内存中的嵌套引用。如果某个嵌套复合体尚未加载（除 `main.composite`以外的任何复合体；它是场景中唯一随场景打包的复合体），系统会记录一条警告并跳过该分支。若要生成包含嵌套引用的复合体，请先对每个被引用的文件调用 `loadComposite()` ；或者更简单地，只生成自包含的复合体。

## 相关页面

* [实体与组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md) ——复合体所描述的构建模块。
* [自定义物品](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/custom-items.md) ——以复合体形式存储的可复用物品。
* [智能物品 - 高级](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/smart-items-advanced.md#about-spawning-entities) — 使用“生成实体”操作，无需编写代码即可生成复合体。
* [场景文件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/xiang-mu-lei-xing/scene-files.md) — 所在位置： `main.composite` 位于你的场景项目中。


---

# 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/composites.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.
