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

# 在代码中引用物品

通过名称或标签在代码中引用物品。

你可以在代码中引用通过 Creator Hub 拖放界面添加的项目。这对于为这些项目添加复杂行为，或在代码的其他部分引用它们很有用。

## 按名称获取

使用 Creator Hub 将实体拖入画布时，每个实体都有唯一名称。使用 `engine.getEntityOrNullByName()` 函数，即可在代码中引用这些实体。

使用 `EntityNames` 枚举可以轻松访问通过 Creator Hub 添加的实体名称；也可以将名称写成字符串，名称需与场景编辑器中场景实体树视图所显示的内容一致。

```ts
import { EntityNames } from '../assets/scene/entity-names'

function main() {

	// Use the EntityNames enum
	const door1 = engine.getEntityOrNullByName(EntityNames.Door_1)

	// Write the name as a string
	const door2 = engine.getEntityOrNullByName('Door 2')

	// Ensure both doors exist in the scene
	if (door1 && door2) {
		// 
	}

}
```

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

EntityNames `EntityNames` 枚举包含 Creator Hub 添加的所有实体，并会在你进行任何更改后立即更新。如果将 `EntityNames.` 导入代码，IDE 会显示一个下拉列表，其中包含所有可用实体的名称。

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

你也可以使用 `engine.getEntityByName<EntityNames>()` 函数，并传入 `<EntityNames>` 作为 [TypeScript 泛型](https://www.typescriptlang.org/docs/handbook/2/generics.html)，以验证场景中是否确实存在该名称的实体。如果在 Creator Hub 中重命名了所引用的实体，此方法会报错警告。由于此函数的输出不可能是 `null`，因此无需检查该实体是否存在。

```ts
import { EntityNames } from '../assets/scene/entity-names'

function main() {

	const door1 = engine.getEntityByName<EntityNames>(EntityNames.Door_1)

	// No need to check for null
	console.log(Transform.get(door1).position.x)

}
```

{% hint style="warning" %}
**📔 注意**：请确保仅在 `engine.getEntityOrNullByName()` 和 `engine.getEntityByName()` 函数中、在 `main()` 函数中、在其后运行的函数中，或在系统中使用。如果在这些上下文之外使用，场景编辑器中创建的实体可能尚未实例化。 `main()`如果在这些上下文之外使用，场景编辑器中创建的实体可能尚未实例化。
{% endhint %}

使用上述任一方法获取实体引用后，你就可以对其执行任何操作，例如添加或移除组件、修改现有组件的值，甚至从引擎中移除该实体。

```ts
import { EntityNames } from '../assets/scene/entity-names'

function main() {
	// fetch entity
	const door = engine.getEntityOrNullByName(EntityNames.Door_3)
	// verify that the entity exists
	if (door) {
		// add a pointer events callback
		pointerEventsSystem.onPointerDown(
			{
				entity: door,
				opts: { button: InputAction.IA_PRIMARY, hoverText: 'Open' },
			},
			function () {
				// 打开门
			}
		)
	}
}
```

通过场景编辑器添加的所有实体都有一个 `Name` 组件，你也可以像这样遍历所有实体：

```ts
function main() {
	for (const [entity, name] of engine.getEntitiesWith(Name)) {
		console.log({ entity, name })
	}
}
```

## 按标签获取

你也可以按标签获取实体。标签用于将实体分组，便于识别用途或行为相同的实体。

你可以在项目属性面板顶部的 **标签** 部分为实体添加标签。你可以选择通用标签，例如 **标签组 1** 到 **标签组 4**，也可以创建名称更具体的自定义标签。

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

{% hint style="info" %}
**💡 提示**：一个实体可以分配多个标签。

<img src="https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-e111901f37132a7070e8d9729984fa2fa8c43fc3%2Ftags-multiple.webp?alt=media" alt="" data-size="original">
{% endhint %}

然后，你可以使用 `engine.getEntitiesByTag()` 函数获取所有带有指定标签的实体。当你想遍历用途或行为相同的一组实体时，这个函数非常实用。

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

export function main() {
	const taggedEntities = engine.getEntitiesByTag('myTag')
  
	for (const entity of taggedEntities) {
      // 对每个实体执行操作
    }
}
```

你也可以在代码中为实体添加或移除标签。如果你想根据某些逻辑更改标签，或动态生成带有特定标签的实体，这会很有用。

```ts
import { Tags } from '@dcl/sdk/ecs'

Tags.remove(entity, tagName);
Tags.add(entity, tagName);
```

## 获取某个项目的所有子项

获取特定项目的引用后，你就可以获取屏幕左侧实体树中归为其子项的所有项目。以下脚本先获取父实体，然后遍历其所有带有 Transform 组件的子实体。遍历过程中，你可以应用任何自定义逻辑。

```ts
import { engine, Entity, Transform, Name, getEntitiesWithParent } from '@dcl/sdk/ecs'
import { EntityNames } from '../assets/scene/entity-names'

function main() {
	// 获取父实体
	const parent = engine.getEntityByName<EntityNames>(EntityNames.ParentEntity)

	// 获取所有子实体
	const children = getEntitiesWithParent(engine, parent)
	for (const child of children) {
   		// 处理每个子实体
	}
}
```

## 智能物品触发器

你可以检测智能物品的 **触发事件**，并通过自定义代码响应这些事件。例如，你可以放置一个按钮智能物品，并在按钮被点击时执行自定义代码。

使用 `getTriggerEvents` 获取一个对象，用于处理特定智能物品的触发事件，然后使用返回对象的 `.on()` 函数订阅回调函数。每当触发事件发生时，都会执行此回调函数。

例如，如果场景中有一个按钮，其通用事件为 **点击时** 事件中，你可以编写以下代码，以便在按钮每次被触发时运行自定义代码。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-354d0c85d770f5e44c32fcd98ce46783df55ff21%2Frestart-button.webp?alt=media)

```ts
import { engine } from '@dcl/sdk/ecs'
import { getTriggerEvents, getActionEvents } from '@dcl/asset-packs/dist/events'
import { TriggerType } from '@dcl/asset-packs'
import { EntityNames } from '../assets/scene/entity-names'

function main() {
	const restart = engine.getEntityOrNullByName(EntityNames.Restart_Button)
	if (restart) {
		const restart_event = getTriggerEvents(restart)
		restart_event.on(TriggerType.ON_CLICK, () => {
			// restartGame()
		})
	}
}
```

你也可以订阅其他类型的触发事件，例如 **ON\_PLAYER\_ENTERS\_AREA**, **ON\_SPAWN**, **ON\_TWEEN\_END**等。

## 智能物品操作

你可以检测智能物品的 **操作**何时被触发，并通过自定义代码作出响应。例如，你可以放置一个门智能物品，并在 **打开** 操作被调用时运行自定义代码。

使用 `getActionEvents` 获取一个用于处理特定智能物品操作的对象。然后，你可以使用返回对象的 `.on()` 函数订阅回调函数。每当该操作发生时，都会执行此回调函数，无论该操作是由另一个智能物品触发，还是由你自己的自定义代码触发。

例如，如果场景中有一扇门，并且它具有以下默认的 **打开** 操作，你可以编写以下代码，以便在门每次打开时运行自定义代码。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-24c0cf117e2d98d79b272a087da4c815d4ff1a5d%2Fdoor-actions.webp?alt=media)

```ts
import { engine } from '@dcl/sdk/ecs'
import { getTriggerEvents, getActionEvents } from '@dcl/asset-packs/dist/events'
import { TriggerType } from '@dcl/asset-packs'
import { EntityNames } from '../assets/scene/entity-names'

function main() {
	const door = engine.getEntityOrNullByName(EntityNames.Wooden_Door)
	if (door) {
		// detect actions
		const actions = getActionEvents(door)
		actions.on('Open', () => {
			console.log('Door opened!!')
			// custom code
		})

		// detect triggers
		const triggers = getTriggerEvents(door)
		triggers.on(TriggerType.ON_CLICK, () => {
			console.log('Door clicked!!')
			// custom code
		})
	}
}
```

你还可以在代码中发出操作事件，这样就能利用智能物品「操作」组件中已定义的操作。以下代码片段会在按钮智能物品被触发时，调用门智能物品的“打开”操作。

```ts
import { engine } from '@dcl/sdk/ecs'
import { getTriggerEvents, getActionEvents } from '@dcl/asset-packs/dist/events'
import { TriggerType } from '@dcl/asset-packs'
import { EntityNames } from '../assets/scene/entity-names'

function main() {
	const button = engine.getEntityOrNullByName(EntityNames.Red_Button)
	const door = engine.getEntityOrNullByName(EntityNames.Wooden_Door)
	if (button && door) {
		// references to actions and triggers
		const buttonTriggers = getTriggerEvents(button)
		const doorActions = getActionEvents(door)

		// detect triggers on button
		buttonTriggers.on(TriggerType.ON_INPUT_ACTION, () => {
			// 打开门
			doorActions.emit('Open', {})
		})
	}
}
```

{% hint style="info" %}
**💡 提示**：如果你不打算实现特别复杂的功能，也可以创建自定义智能物品来处理所需操作，而无需编写代码。请参阅 [让任何物品变得智能](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/make-any-item-smart.md).
{% endhint %}

## 其他智能物品组件

智能物品可以包含 asset-packs 库中的特殊组件，例如 `States` 或 `Counter`。这些组件不属于 Decentraland SDK，但可以通过库中的 `getComponents()` 函数获取。然后，你可以在场景代码中读取或写入这些组件的值，从而让智能物品的行为与代码实现更紧密地集成。

下面的示例会在宝箱智能物品的操作被触发时，读取并记录其 State 组件的值。

```ts

import { engine } from '@dcl/sdk/ecs'
import { getComponents } from '@dcl/asset-packs'
import { getTriggerEvents } from '@dcl/asset-packs/dist/events'
import { TriggerType } from '@dcl/asset-packs'
import { EntityNames } from '../assets/scene/entity-names'


export function main() {

    const chest = engine.getEntityByName<EntityNames>(EntityNames.chest)
 
    if (chest) {

        const chestTriggers = getTriggerEvents(chest)

        chestTriggers.on(TriggerType.ON_INPUT_ACTION, () => {
            const { States } = getComponents(engine)
            let state = States.getMutableOrNull(chest)?.currentValue
            console.log( "chest new state ", state)
        })
    }
}
```


---

# 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/reference-items.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.
