> 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/you-hua/pre-load-resources.md).

# 预加载资源

预加载资源可以让资源在场景启动时就被下载好，这样玩家第一次与它们交互时就已准备就绪。

在某些情况下，资源会被添加到场景中，但不会立即使用。例如，音频文件可能只会在玩家按下按钮时播放。在这种情况下，玩家第一次按下按钮时，音频可能会晚几秒播放，因为文件只有在需要时才会下载。

为避免此问题，请使用 `AssetLoad` 组件，确保这些资源在需要之前已下载并可供使用。

```ts
import { AssetLoad } from "@dcl/sdk/ecs"

AssetLoad.create(engine.RootEntity, {
  assets: [
    "assets/scene/bundle1/explosionSound.mp3",
    "assets/scene/bundle1/explosion.glb",
  ],
})
```

列在 `AssetLoad` 组件中的资源会被下载并加入内存，确保场景需要加载它们时可立即使用。

一些重要注意事项：

* 你可以将 `AssetLoad` 组件放在任何实体上（不仅仅是 RootEntity），并且可以根据需要在多个实体上使用它。这对于处理场景中不同层级或区域的独立加载状态很有帮助。
* 该 `AssetLoad` 组件用于将资源添加到内存中，而不是移除它们。将资源从 `AssetLoad.create` 中移除不会释放内存。
* 如果某个资源在场景加载时会立即使用（例如，放置在场景中的 GLB 模型，或持续播放的背景音效），则无需使用 `AssetLoad` 组件，因为它已经在下载中了。
* 向 `AssetLoad.create`添加资源时请注意，只预加载在场景启动时不需要的资源，以避免不必要的性能开销。
* 你只能预加载作为场景文件一部分上传的资源。此功能无法用于预加载来自外部 URL 的图片

## 响应加载状态

如果你的场景能够对每个资源何时完成下载做出响应，那么预加载资源会更有用。例如，你可能希望一直显示加载界面，直到所有资源都准备就绪，向玩家显示进度，或者优雅地处理某个下载失败的资源。

要跟踪这一点，请使用 `assetLoadLoadingStateSystem`。调用其 `registerAssetLoadLoadingStateEntity` 方法，并传入持有 `AssetLoad` 组件的实体以及一个回调函数。每当该实体某个资源的加载状态发生变化时，回调函数都会运行。

```ts
import {
  AssetLoad,
  LoadingState,
  assetLoadLoadingStateSystem,
} from "@dcl/sdk/ecs"

const preloader = engine.addEntity()
AssetLoad.create(preloader, {
  assets: [
    "assets/scene/bundle1/explosionSound.mp3",
    "assets/scene/bundle1/explosion.glb",
  ],
})

assetLoadLoadingStateSystem.registerAssetLoadLoadingStateEntity(
  preloader,
  (assetLoadState) => {
    console.log(
      `Asset ${assetLoadState.asset} is now: ${assetLoadState.currentState}`
    )
  }
)
```

回调函数会接收一个包含以下属性的对象：

* `asset`：状态发生变化的资源路径。这与您在 `AssetLoad` 组件。
* `currentState`来自 `LoadingState` 枚举中的值，用于描述该资源的新状态。

该 `LoadingState` 枚举可以包含以下值：

* `LoadingState.LOADING`：资源正在下载中。
* `LoadingState.FINISHED`：资源已成功下载并可供使用。
* `LoadingState.FINISHED_WITH_ERROR`：找到了该资源，但在下载时发生了错误。
* `LoadingState.NOT_FOUND`：在提供的路径下未找到任何资源。
* `LoadingState.UNKNOWN`：资源状态未知。

以下示例使用加载状态，根据资源预加载的进度来改变实体的颜色：

```ts
import {
  AssetLoad,
  LoadingState,
  Material、
  assetLoadLoadingStateSystem,
} from "@dcl/sdk/ecs"
import { Color4 } from "@dcl/sdk/math"

function getLoadingColor(state: LoadingState): Color4 {
  switch (state) {
    case LoadingState.FINISHED:
      return Color4.Green()
    case LoadingState.LOADING:
      return Color4.Yellow()
    case LoadingState.FINISHED_WITH_ERROR:
    case LoadingState.NOT_FOUND:
      return Color4.Red()
    default:
      return Color4.Gray()
  }
}

assetLoadLoadingStateSystem.registerAssetLoadLoadingStateEntity(
  preloader,
  (assetLoadState) => {
    Material.setPbrMaterial(myEntity, {
      albedoColor: getLoadingColor(assetLoadState.currentState),
    })
  }
)
```

{% hint style="info" %}
**💡 提示**：你可以向现有的 `AssetLoad` 组件中添加更多资源，例如在响应玩家操作时。使用 `AssetLoad.getOrCreateMutable()` 来获取该组件，并将新的路径推入其 `assets` 数组中。注册的回调函数也会在这些新添加的资源下载时触发。
{% endhint %}

{% hint style="info" %}
**💡 提示**：关于此组件的可运行示例，请参见 [`88,-12-asset-load`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/88,-12-asset-load) 测试场景，它通过一个预加载 mp3、纹理、视频和 glb 的 `AssetLoad` 组件，并通过其报告每个资源的状态 `assetLoadLoadingStateSystem` ——其中包括一个故意缺失的路径，其解析结果为 `NOT_FOUND`.
{% endhint %}


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/you-hua/pre-load-resources.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
