> 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-bian-ji-qi/shi-yong-dai-ma-kuo-zhan/script-component.md).

# 使用脚本组件

使用 Script 组件为代码赋予功能，而无需深入整个项目结构。

借助新的 Script Component，可以创建能够在实体内部执行自定义代码的实体。

Script Component 让实体无需直接操作 `index.ts` 以及可能涉及的其他文件，即可执行自定义行为。

## 设置 Script Component

1. 点击 `+` 按钮，将 Script Component 添加到实体。点击 **+ Add New Script Module** 创建脚本并为其命名，或者使用 File Path（浏览文件或拖放现有文件）。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-0a4b3eb7762a7f26eb37f920671705a1007d907f%2Fnew-script-component.webp?alt=media)

2. 点击组件中的 CODE 按钮，打开默认代码编辑器。下面来了解一下它的结构。有关如何选择和管理默认编辑器的详细信息，请参阅 [与代码结合](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/shi-yong-dai-ma-kuo-zhan/overview.md).

## 了解 Script 的结构

首次打开 Script 时，其中包含以下代码：

```ts
import { engine, Entity } from '@dcl/sdk/ecs'
import {} from '@dcl/sdk/math'

export class BuildingScript {
  /**
   * 属性
   * 定义要在多个方法中重复使用的类字段。
   * 用法示例：this.myVariable
   */
   // private myVariable: boolean = true

  /**
   * 构造函数 / 输入项
   * 在此处声明的参数会显示在 Creator Hub 的 Script 组件 UI 中。
   * 支持的类型：Entity、String、Number、Boolean、ActionCallback 和 Slider
   * 对于使用滑块编辑的数字，例如：public speed: Slider<0, 10, 0.5> = 1
   *
   * 注意：编辑此文件后，请点击 Script 组件 UI 中的刷新图标
   * 以查看更新后的输入项。
   *
   * 构造函数中的 `src` 和 `entity` 字段是内部引用所必需的。
   */
  constructor(
    public src: string,     // DO NOT REMOVE
    public entity: Entity,   // DO NOT REMOVE
    // Add your custom inputs below
  ) {}

  /**
   * start()
   * 脚本初始化时调用一次。
   */
  start() {
    // 脚本初始化
    console.log("BuildingScript initialized for entity:", this.entity);
  }

  /**
   * update(dt)
   * 每帧调用。
   * @param dt -（可选）自上一帧以来经过的时间（秒）
   */
  update(dt: number) {
    // 每帧调用
  }
}
```

该类由三个主要部分组成：

* &#x20;**constructor**,
* &#x20;**start()** 方法
* &#x20;**update()**  方法。

## 构造函数

构造函数包含你希望在 Creator Hub 中通过场景公开并动态修改的参数。

```ts
export class BuildingScript {
  constructor(
    public src: string,
    public entity: Entity,
    public numericVariable: number, 
  ) {}
...
}
```

保存文件后，Script Component 中的 **刷新** 按钮会应用所有更改。

<img src="https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-8f1b521e1b68b5d9138dd1b60eeb40e4b13dbb0c%2Fscript-refresh-button.webp?alt=media" alt="刷新按钮" width="360">

刷新后，脚本组件现在会显示代码中添加的 `numericVariable` 。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-18eb30b39910dc3dacecb48e7c6e6c3a26551c4a%2Fparameter-script-component.webp?alt=media)

## 参数

如果不同实体在脚本组件中使用同一个文件，它们仍各自拥有独立的参数：如果场景中有两栋建筑， `building1` 和 `building2`，且二者的脚本组件都指向 `BuildingScript.ts` 文件，那么每栋建筑都有自己的 `numericVariable` 参数，可以分别修改。

{% hint style="warning" %}
**重要提示**：请勿修改或删除 `public src: string` 和 `public entity: Entity`。你可以在这些参数后面添加新的输入项。
{% endhint %}

构造函数参数允许使用以下类型：

* `Entity`
* `string`
* `number`
* `boolean`
* `ActionCallback`
* `Slider<Min, Max, Step>`
* 字符串选项，例如 `'small' | 'large'`
* 对象，例如 `{ x: number; y: number }`
* 列表，例如 `string[]` 或 `Array<{ entity: Entity; label: string }>`

Creator Hub 会将每个参数名转换为易读的标签： `maxHealth` 显示为 **最大生命值**.

### 带滑块的数值参数

将数值参数的类型设为 `Slider<Min, Max, Step>` 即可使用滑块编辑，而不是普通的数字输入框。Creator Hub 会同时显示滑块和数字输入框。

```ts
constructor(
  public src: string,
  public entity: Entity,
  // 从 0 到 10 的滑块，步长为 0.5
  public speed: Slider<0, 10, 0.5> = 1,
) {}
```

* `Step` 是可选的，默认值为 `1`.
* 允许使用负数边界，例如 `Slider<-90, 90>`.
* 运行时，该值是普通的 `number`，因此 `this.speed` 与其他数字参数的行为相同。

{% hint style="info" %}
**📔 注意**：无论是 `public` 还是 `private` 构造函数参数都会显示在 Creator Hub 中。 `private` 关键字只限制在 `BuildingScript` 类中的访问权限。更多详情，请参阅 TypeScript 官方文档中的\
[参数属性](https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties).
{% endhint %}

### 选项参数

将字符串参数类型声明为字符串联合类型，即可通过下拉菜单编辑。默认值是初始选中的选项。

```ts
constructor(
  public src: string,
  public entity: Entity,
  // 包含三个选项的下拉菜单，初始选中 'player'
  public target: 'all' | 'player' | 'non_player' = 'player',
) {}
```

### 将参数分组到对象中

将参数声明为对象，即可将其字段显示在同一组中，并可展开和折叠。分组默认处于折叠状态。

```ts
constructor(
  public src: string,
  public entity: Entity,
  // 显示为包含 X、Y 和 Z 字段的“生成点”分组
  public spawnPoint: { x: number; y: number; z: number } = { x: 8, y: 0, z: 8 },
) {}
```

对象可以包含其他对象和列表。像上面这样直接内联写出结构：Creator Hub 不会读取命名类型，因此使用在别处声明的 `interface` 或 `type` 别名声明的参数不会显示其字段。

### 列表参数

将参数声明为数组，即可让创作者按需添加任意数量的行。每行都有一个垃圾桶按钮，而 **添加** 按钮可添加新行。

```ts
constructor(
  public src: string,
  public entity: Entity,
  // 每行包含一个实体选择器和一个文本字段
  public targets: Array<{ entity: Entity; label: string }> = [],
) {}
```

`T[]` 和 `Array<T>` 作用相同。

### 使用标签缩小选择器范围

在参数前，或在对象参数的字段前紧邻处的 `/** */` 注释中添加以下标签之一，即可更改 Creator Hub 编辑该参数的方式。对于列表，标签会应用于每一行。

| 标签                     | 适用对象        | 功能                                   |
| ---------------------- | ----------- | ------------------------------------ |
| `@components <name> …` | 一个 `Entity` | 仅提供包含所列组件之一的实体。                      |
| `@actionsOf <field>`   | 一个 `string` | 显示一个下拉菜单，其中包含同级字段中所选实体的操作 `<field>`. |
| `@format wallet`       | 一个 `string` | 将值编辑为钱包地址。                           |

```ts
constructor(
  public src: string,
  public entity: Entity,
  public buttons: Array<{
    /** @components asset-packs::Actions */
    entity: Entity
    /** @actionsOf entity */
    action: string
  }> = [],
  /** @format wallet */
  public owner: string = '',
) {}
```

在此示例中， **按钮** 只允许你选择带有操作的项目，其 **操作** 下拉菜单会列出该行所选项目的操作。在选择项目之前，下拉菜单会显示 **请先选择一个项目**。如果已保存的操作在该项目中已不存在，字段会显示相应提示。

这些标签只会影响编辑器。在运行时，脚本接收的是普通值：一个实体、一个包含操作名称的字符串，以及一个包含地址的字符串。

### 文件参数

字符串参数可以保存随脚本一起提供的文件名，例如音效或模型。脚本会从自身文件夹中读取该文件，例如 `` `${this.src}/${this.sound}` ``。请参阅 [默认参数](#default-parameters).

Creator Hub 会检查这些值。如果某个值指向应当位于脚本文件夹中、但实际不存在的文件，字段会显示 `"<file name>" is missing`。URL 和普通文本不会触发提示。

当你在 **本地资源** 标签页中重命名或移动脚本文件夹内的文件时，引用该文件的参数会自动更新；删除文件时，系统会提醒你该文件正在使用。将文件移出脚本文件夹后，系统无法跟踪其位置，Creator Hub 会提示你有些引用无法更新。

### 在脚本中访问参数

要在代码中访问参数值，请使用以下格式： `this.definedParameter`例如： `this.numericVariable` 或 `this.entity`.

默认脚本模板在 start() 方法中包含以下代码行：

`console.log("BuildingScript initialized for entity:", this.entity);`.

要记录你在构造函数中定义的值，请按如下方式修改：

`console.log("BuildingScript initialized with numericVariable:`, `this.numericVariable);`

请注意，当你在 Creator Hub 界面中更改参数值时，日志中显示的值也应随之变化。

### 默认参数

默认情况下，构造函数中包含一个 `src` 和一个 `entity` 参数，它们对脚本代码非常有用：

* `this.entity` 始终指向包含 `Script` 组件，用它来访问有关该实体的信息，或向其添加组件。
* `this.src` 是脚本的存储路径。创建供他人使用的智能物品时，这尤其有用。使用此字段构造智能物品中随附文件的路径，即使智能物品的路径发生变化或被重命名，也能正常工作。

```ts
export class BuildingScript {
  constructor(
    public src: string,
    public entity: Entity,
  ) {}

  start() {
    Material.setPbrMaterial(this.entity, {
      texture: Material.Texture.Common({
        src: this.src + '/images/myImage.png',
      })
    });
  }
}
```

上述脚本会获取拥有该脚本的实体，并为其应用纹理。它从智能物品文件夹中随附的一个 `.png` 文件中获取纹理。该文件位于名为 `/images`的子文件夹中。使用 `this.src`后，无论智能物品导入场景时位于 `/assets/custom/itemName` 还是 `/assets/asset-packs/itemName`

### 参数提示

为输入参数添加提示，帮助用户了解这些字段的用途或可接受的值。用户会在 Script 组件界面的每个字段旁看到提示图标，将鼠标悬停在图标上即可阅读自定义说明。

要为构造函数添加提示，请在构造函数前添加一段注释，并为每条提示写一行 `@param` ，后接字段名称和说明。

```ts
  /**
   * @param startDate - 活动开始日期，格式为 YYYY-MM-DD
   * @param yOffset - 物品在地面上方显示的高度（米）
   */
  constructor(
    public src: string,
    public entity: Entity,
    public startDate?: string,
    public yOffset: number = 0.5,
  ) {
  }
```

你可能需要点击 Script 组件界面中的刷新图标，才能看到提示内容的更改。

<img src="https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-8f1b521e1b68b5d9138dd1b60eeb40e4b13dbb0c%2Fscript-refresh-button.webp?alt=media" alt="刷新按钮" width="360">

## start() 和 update() 方法

&#x20;**start()** 方法中的代码只会执行一次，即在实体创建时执行（本例中是在场景首次加载时）。

预览场景并查看日志（**提示**：你可以使用 `` ` `` 快捷键）：日志会显示新消息，其中包括 `numericVariable` 参数。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-fabd7facf4936fb649ae429b9c37fc419ba7d0b6%2Fscript-log-message.webp?alt=media)

&#x20;**update()** 方法则不同，它会在游戏的每一帧执行代码（与 Systems 一样）。例如，可以检查 `PlayerEntity` 的值，以触发脚本中的行为。

以下代码会在游戏的每一帧输出日志，前提是 `PlayerEntity` 高于之前定义的 `numericVariable`。该值由创建者通过 Script 组件界面动态提供。

```ts
update(dt: number) {
    if (Transform.get(engine.PlayerEntity).position.y > this.numericVariable ) {
      console.log("The player's height is over ", this.numericVariable);
    }}
```

<img src="https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-7825c3d4095279d79c52337e7210e1935f796703%2Fupdate-script-logs.webp?alt=media" alt="Update Method" data-size="line">

第一条日志属于 start() 方法，表示我们设置了 numericVariable。第二条属于 update() 方法，在玩家高度超过该值时输出。

## 向 Creator Hub 暴露操作

可以定义一个 `Action` 在 Script Component 脚本中，并使其可在 Creator Hub 的界面中使用。这样便可以通过另一个 Entity 触发此操作。 `Action` 与另一个 Entity 一起使用。

```ts
  /**
   * 将此操作设为可触发
   * @action
   */
  exposedAction(creatorHubParameter: number) {
    console.log("Triggered from another entity using parameter: ", this.creatorHubParameter);
  }
```

`creatorHubParameter` 将作为一个 `Action` 参数公开，以便为其设置自定义值。刷新 Script Component 后，新操作将显示在 Actions 下拉菜单中，供你选择。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-b2347abdf8b6704b2c7b1f7090de49b535beaf5d%2Fscript-component-action.webp?alt=media)

添加 Action 后，Creator Hub 中的任何 Entity 都可以使用 `Triggers`

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-d5af1dd8d6a6bbf64f9202976f66bfab49e65189%2Fscript-component-action-trigger.webp?alt=media)

{% hint style="info" %}
**📔 注意**：你可以在脚本中添加任意数量的 Action。每个 Action 都可以通过各自独立的 `Action` 下拉菜单访问。
{% endhint %}

## 从外部调用 Script 方法

若要从另一个 Script 或从 `src/index.ts`调用 Script 方法，请按以下步骤操作：

1. 在 Script 类中创建一个 `public` 方法。
2. 在场景根目录中运行 `npm run build` 。
3. 在要使用该 public 方法的文件中，添加 `import { callScriptMethod } from '~sdk/script-utils'`.
4. 使用所需参数调用 `callScriptMethod` （此处为 `someParamter`).

下面是一个公开 `public` 方法的示例：

```ts
export class BuildingScript {
  constructor(
    public src: string,
    public entity: Entity,
    ...,
  ) {}

  public publicMethod(boolParameter: boolean, someNumberParameter: number) {
    if (boolParameter) {
      console.log("Public method called with parameter true!: ", someNumberParameter);
    } else {
      console.log("Public method called with parameter: false!", someNumberParameter);
    }
  }
...
}
```

若要从 `src/index.ts`调用该方法，请使用：

```ts
import { callScriptMethod } from '~sdk/script-utils'


export function main() {
    const buildingEntity = engine.getEntityOrNullByName("building")
    if (buildingEntity) {
        const scriptMethod = callScriptMethod(
            buildingEntity,
            "assets/scene/Scripts/BuildingScript.tsx",
            "publicMethod",
            false,
            3,
        )

        scriptMethod
    }
}
```

首先， `main` 函数会查找带有 Script 组件的 `Entity` 。其次，如果存在， `Entity` （原文未提供对应标识符） `callScriptMethod` 会使用以下参数调用：

1. `entity`: `Entity` ，它具有该 `public` 方法。
2. `scriptPath`: `path` ， `Script` 类所在的位置。
3. `methodName`：要调用的 `public` 方法的名称。
4. `...args`：方法的参数。本例中有两个参数，应按顺序依次添加。

第三，我们调用定义的 `callScriptMethod`，本例中是 `scriptMethod`.

给定参数值后，输出如下：

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-761e5092a6f0de732888f475223cd391bf158f46%2Fscript-component-public-method.webp?alt=media)

{% hint style="info" %}
**📔 注意**：你可以按照相同的逻辑，从另一个脚本或文件调用 `public` Script 方法。你可以用它获取或更改 `public` Script 类中的变量值。
{% endhint %}

## 从脚本触发其他 Entity 的操作

可以在 Script 类构造函数中使用类型为 `ActionCallback` 的参数。这样就可以从 Script 的方法中触发另一个 `Entity`的 `Action` ，该操作通过 Creator Hub UI 定义。

在此示例中， `anotherEntityAction` 被添加为一个 `public` 参数。

```ts
export class BuildingScript {
  constructor(
    public src: string,
    public entity: Entity,
    public anotherEntityAction: ActionCallback,
    ...,
  ) {}
  ...
}
```

可选择的 `Entity` 和 `Action` 现在可以在 Creator Hub UI 中刷新 Script Component 时使用。 `Sphere` 是场景中已存在的 Entity，其中包含一个名为 `Scale`.

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-eebee3acf257773a5b63ed040f18d1010a481420%2Fscript-component-action-callback.webp?alt=media)

现在可以在 Script 类中访问另一个 Entity 的 action。它有许多不同的用法。在下面的示例中，按 E 将触发 `this.anotherEntityAction` 方法是定义一个 `pointerEventsSystem` 并在 `start` 方法中进行设置。

```ts
  start() {
    pointerEventsSystem.onPointerDown(
      {
        entity: this.entity,
        opts: {
          button: InputAction.IA_PRIMARY,
          hoverText: "按 E 可触发来自另一个 Entity 的 Action。",
        },
      },
      () => {
        this.anotherEntityAction();
      }
    );
  }
```

### 可选的 action 回调

如果创建者未连接某个 `ActionCallback` 参数，该参数的值为 `undefined`，其类型为 `ActionCallback | undefined`调用前请先检查该参数，确保无论 action 是否已连接，脚本都能正常运行：

```ts
if (this.anotherEntityAction) {
  this.anotherEntityAction();
}
```

{% hint style="info" %}
**📔 注意**：结合公开与触发 `Actions` 是一项非常强大的工具。你可以在一个 Entity 上定义 Script Component，使用 `public` 方法公开一个 action，然后在另一个 Entity 的 Script Component 中通过 `ActionCallback` 参数触发它。
{% endhint %}

## 另请参阅

* [智能项目 - 基础](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/smart-items.md)
* [智能项目 - 进阶](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/smart-items-advanced.md)
* [状态与条件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/states-and-conditions.md)
* [让任何项目变得智能](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/make-any-item-smart.md)
* [SDK 快速入门](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/sdk-101.md)：跟随本迷你教程，快速了解基础知识。
* [开发工作流](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/dev-workflow.md)：阅读本文，了解从头到尾创建场景的完整流程。
* [示例](https://docs.decentraland.org/creator/content-creator-zh/jiao-cheng-yu-shi-li/examples.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-bian-ji-qi/shi-yong-dai-ma-kuo-zhan/script-component.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.
