> 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-ko/scene-editor/extend-with-code/reference-items.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 코드에서 아이템 참조

이름이나 태그로 코드에서 아이템을 참조합니다.

Creator Hub의 드래그 앤 드롭 인터페이스를 통해 추가한 항목을 코드에서 참조할 수 있습니다. 이러한 항목에 정교한 동작을 추가하거나 코드의 다른 부분에서 참조할 때 유용합니다.

## 이름으로 가져오기

Creator Hub에서 엔티티를 캔버스로 드래그해 추가하면 각 엔티티에 고유한 이름이 지정됩니다. 다음 `engine.getEntityOrNullByName()` 함수를 사용하면 코드에서 이러한 엔티티 중 하나를 참조할 수 있습니다.

다음 `EntityNames` 열거형을 사용하면 Creator Hub에서 추가한 엔티티의 이름에 쉽게 접근할 수 있습니다. 또는 Scene Editor의 장면 엔티티 트리 뷰에 표시된 이름을 문자열로 작성할 수도 있습니다.

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

function main() {

	// EntityNames 열거형 사용
	const door1 = engine.getEntityOrNullByName(EntityNames.Door_1)

	// 이름을 문자열로 작성
	const door2 = engine.getEntityOrNullByName('Door 2')

	// 장면에 두 문이 모두 있는지 확인
	if (door1 && door2) {
		// 
	}

}
```

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

Creator Hub에서 추가한 모든 엔티티의 전체 목록이 포함된 `EntityNames` 열거형은 변경 사항이 발생할 때마다 즉시 업데이트됩니다. 코드에서 `EntityNames.` 를 가져오면 IDE에서 사용 가능한 모든 엔티티 이름이 드롭다운으로 표시됩니다.

![](https://3980763956-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)

	// null인지 확인할 필요 없음
	console.log(Transform.get(door1).position.x)

}
```

{% hint style="warning" %}
**📔 참고**: 다음 함수는 `engine.getEntityOrNullByName()` 및 `engine.getEntityByName()` 를 `main()` 함수 내부, 이후에 실행되는 함수 내부 또는 시스템에서만 사용해야 합니다. `main()`이러한 컨텍스트 밖에서 사용하면 Scene Editor에서 만든 엔티티가 아직 인스턴스화되지 않았을 수 있습니다.
{% endhint %}

위 메서드 중 하나로 엔티티 참조를 가져오면 컴포넌트 추가 또는 제거, 기존 컴포넌트 값 수정, 엔진에서 엔티티 제거 등 원하는 작업을 자유롭게 수행할 수 있습니다.

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

function main() {
	// 엔티티 가져오기
	const door = engine.getEntityOrNullByName(EntityNames.Door_3)
	// 엔티티가 있는지 확인
	if (door) {
		// 포인터 이벤트 콜백 추가
		pointerEventsSystem.onPointerDown(
			{
				entity: door,
				opts: { button: InputAction.IA_PRIMARY, hoverText: '열기' },
			},
			function () {
				// 문 열기
			}
		)
	}
}
```

Scene Editor를 통해 추가된 모든 엔티티에는 `Name` 컴포넌트가 있습니다. 다음과 같이 모든 엔티티를 순회할 수도 있습니다:

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

## 태그로 가져오기

태그를 사용해 엔티티를 가져올 수도 있습니다. 태그는 엔티티를 그룹화하는 방법이며, 용도나 동작이 같은 엔티티를 식별하는 데 유용합니다.

다음 항목을 통해 엔터티에 태그를 추가하세요. **태그** 항목 속성 패널 상단의 섹션에서 추가할 수 있습니다. 다음과 같은 일반 태그를 선택할 수 있습니다. **태그 그룹 1** 부터 **태그 그룹 4**까지 선택하거나, 더 구체적인 이름으로 직접 만들 수 있습니다.

![](https://3980763956-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://3980763956-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://3980763956-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** 등

## 스마트 아이템 액션

스마트 아이템의  **액션**이 활성화되는 것을 감지하고 사용자 지정 코드로 대응할 수 있습니다. 예를 들어 문 스마트 아이템을 배치하고  **Open**  액션이 호출될 때마다 사용자 지정 코드를 실행할 수 있습니다.

다음  `getActionEvents` 를 사용하여 특정 스마트 아이템의 액션을 처리할 객체를 가져옵니다. 그런 다음 반환된 객체의  `.on()`  함수를 사용하여 콜백 함수를 구독할 수 있습니다. 이 콜백 함수는 다른 스마트 아이템이나 직접 작성한 사용자 지정 코드 중 무엇이 액션을 활성화했는지에 관계없이 액션이 발생할 때마다 실행됩니다.

예를 들어 씬에 다음과 같은 기본  **Open**  액션이 있는 문이 있다면, 문이 열릴 때마다 사용자 지정 코드를 실행하도록 아래 코드를 작성할 수 있습니다.

![](https://3980763956-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) {
		// 액션 감지
		const actions = getActionEvents(door)
		actions.on('Open', () => {
			console.log('Door opened!!')
			// 사용자 지정 코드
		})

		// 트리거 감지
		const triggers = getTriggerEvents(door)
		triggers.on(TriggerType.ON_CLICK, () => {
			console.log('Door clicked!!')
			// 사용자 지정 코드
		})
	}
}
```

코드에서 액션 이벤트를 발생시킬 수도 있습니다. 이를 통해 스마트 아이템의 Action 컴포넌트에 이미 정의된 액션을 활용할 수 있습니다. 다음 코드는 버튼 스마트 아이템이 트리거될 때마다 문 스마트 아이템의 "Open" 액션을 호출합니다.

```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) {
		// 액션과 트리거에 대한 참조
		const buttonTriggers = getTriggerEvents(button)
		const doorActions = getActionEvents(door)

		// 버튼의 트리거 감지
		buttonTriggers.on(TriggerType.ON_INPUT_ACTION, () => {
			// 문 열기
			doorActions.emit('Open', {})
		})
	}
}
```

{% hint style="info" %}
**💡 팁**: 매우 복잡한 작업이 아니라면 코드를 작성하는 대신 수행하려는 액션을 처리할 사용자 지정 스마트 아이템을 만들 수도 있습니다. 다음을 참조하세요:  [모든 아이템을 스마트하게 만들기](https://docs.decentraland.org/creator/content-creator-ko/scene-editor/interactivity/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-ko/scene-editor/extend-with-code/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.
