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

# 스크립트 컴포넌트 사용

프로젝트 전체 구조를 파고들 필요 없이 코드 기능을 부여하려면 Script 컴포넌트를 사용하세요.

새로운 Script Component를 사용하면 엔티티 자체 내부에서 사용자 지정 코드를 실행하는 엔티티를 만들 수 있습니다.

Script Component를 사용하면 다음 작업을 직접 수행할 필요 없이 엔티티의 사용자 지정 동작을 실행할 수 있습니다. `index.ts` 그리고 잠재적으로 다른 파일들도.

## Script Component 설정하기

1. 다음 항목을 클릭하여 엔티티에 Script Component를 추가하세요. `+` 버튼을 선택하세요. 다음 항목을 클릭하여 새 Script를 만드세요. **+ 새 Script 모듈 추가** 그리고 이름을 선택하거나, File Path를 사용하세요(기존 파일을 찾아보거나 드래그 앤 드롭).

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-79378b201ff5d7fd7334d821c9c2ab0224da46b8%2Fnew-script-component.png?alt=media\&token=a70edded-3a9e-442e-90ce-271a4554b704)

2. 컴포넌트의 CODE 버튼을 클릭하여 기본 코드 편집기를 여세요. 구조를 살펴봅시다. 기본 편집기를 선택하고 관리하는 방법에 대한 자세한 내용은 다음을 참조하세요. [코드와 결합](/creator/content-creator-ko/scene-editor/extend-with-code/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 component UI에 표시됩니다.
   * 지원되는 유형: Entity, String, Number, Boolean, ActionCallback, Slider
   * 슬라이더로 편집되는 숫자의 경우, 예: public speed: Slider<0, 10, 0.5> = 1
   *
   * 참고: 이 파일을 편집한 후 Script component UI에서 새로고침 아이콘을 클릭하세요.
   * 업데이트된 입력을 보려면.
   *
   * 생성자에서 `src`와 `entity` 필드는 내부 참조를 위해 필요합니다.
   */
  constructor(
    public src: string,     // 삭제하지 마세요
    public entity: Entity,   // 삭제하지 마세요
    // 아래에 사용자 지정 입력을 추가하세요
  ) {}

  /**
   * start()
   * 스크립트가 초기화될 때 한 번 호출됩니다.
   */
  start() {
    // 스크립트 초기화
    console.log("BuildingScript initialized for entity:", this.entity);
  }

  /**
   * update(dt)
   * 매 프레임 호출됩니다.
   * @param dt - (선택 사항) 이전 프레임 이후 경과한 델타 시간(초)
   */
  update(dt: number) {
    // 매 프레임 호출됨
  }
}
```

이 클래스는 세 가지 주요 부분으로 구성됩니다:

* 이 **constructor**,
* the **start()** 메서드
* the **update()** 메서드.

## 생성자

생성자에는 Creator Hub에서 장면을 통해 동적으로 노출하고 수정하려는 매개변수가 들어 있습니다.

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

파일이 저장되면 **새로고침** 버튼이 수행한 모든 변경 사항을 업데이트합니다.

<img src="https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-0e88676864e337ab55bf98ae8bd23e2775ec0c60%2Fscript-refresh-button.png?alt=media" alt="새로고침 버튼" width="360">

새로고침이 완료되면 Script Component에 이제 다음이 표시됩니다. `numericVariable` 코드에 추가됨.

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-8729a660cd9b4cd056ff33ad0a28fefe1b7814b1%2Fparameter-script-component.png?alt=media\&token=5dfa1800-9999-4809-ac67-53bc9a7c8671)

## 매개변수

다른 엔티티들이 Script component에서 같은 파일을 사용하더라도, 각각은 여전히 독립적인 매개변수를 가집니다. 장면에 두 개의 건물이 있고, `building1` 과 `building2`가 있으며 둘 다 다음을 가리키는 Script Component를 가지고 있다면 `BuildingScript.ts` 파일, 각 건물은 고유한 `numericVariable` 독립적으로 수정할 수 있는 매개변수를 가집니다.

{% hint style="warning" %}
**중요 참고**: 다음을 수정/삭제하지 마세요 `public src: string` 과 `public entity: Entity`. 이러한 항목 뒤에 새 입력을 추가할 수 있습니다.
{% endhint %}

생성자 매개변수에 허용되는 유형은 다음과 같습니다:

* `Entity`
* `문자열`
* `number`
* `불리언`
* `ActionCallback`
* `Slider<Min, Max, Step>`

### 슬라이더가 있는 숫자 매개변수

숫자 매개변수를 다음과 같이 입력하세요 `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 %}

### 스크립트 안에서 매개변수에 접근하기

코드에서 매개변수 값에 접근하려면 다음 표기법을 사용하세요. `this.definedParameter`. 예: `this.numericVariable` 또는 `this.entity`.

기본 Script 템플릿에는 start() 메서드에 다음 줄이 포함되어 있습니다:

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

생성자에서 정의한 값의 값을 기록하려면 다음처럼 바꾸세요:

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

Creator Hub UI에서 매개변수 값을 변경하면, 기록된 값도 그에 맞게 반영되는 것을 볼 수 있어야 합니다.

### 기본 매개변수

생성자에는 기본적으로 다음이 포함됩니다. `src` 및 `엔티티` 매개변수이며, 이는 스크립트 코드에 매우 유용합니다:

* `this.entity` 항상 다음을 보유한 엔티티를 가리킵니다. `Script` 컴포넌트이며, 이를 사용해 엔티티에 대한 정보를 접근하거나 컴포넌트를 추가하세요.
* `this.src` 는 스크립트가 저장된 경로입니다. 이는 다른 사람이 사용하도록 만들어진 Smart Item을 만들 때 특히 유용합니다. Smart Item의 경로가 변경되거나 이름이 바뀌더라도, 이 필드를 사용하여 Smart Item과 함께 패키징된 파일의 경로를 구성하세요.

```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 component UI에서 각 필드 옆에 있는 툴팁 아이콘을 보고, 아이콘 위에 마우스를 올리면 사용자 지정 텍스트를 읽을 수 있습니다.

생성자에 툴팁을 추가하려면 생성자 바로 앞에 주석 처리된 블록을 추가하고, 각 툴팁마다 다음이 포함된 줄을 작성하세요. `@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 component UI에서 새로고침 아이콘을 클릭해야 할 수 있습니다.

<img src="https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-0e88676864e337ab55bf98ae8bd23e2775ec0c60%2Fscript-refresh-button.png?alt=media" alt="새로고침 버튼" width="360">

## start() & update() 메서드

이 **start()** 메서드에는 엔티티가 생성될 때(이 경우 장면이 처음 로드될 때) 한 번만 실행되는 코드가 들어 있습니다.

장면을 미리 보고 로그를 확인하세요(**팁**: 다음을 사용할 수 있습니다. `` ` `` 바로가기): 새 메시지와 함께 `numericVariable` 파라미터를 설정하여 이미지 파일을 머티리얼의 텍스처로 지정하세요.

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-a8d756ab46337ed47bf6d1d7ae97641abd4cee64%2Fscript-log-message.png?alt=media\&token=4ee0e8a6-7807-44b3-8e86-099e34b39ea7)

이 **update()** 메서드는 반면에 게임의 매 프레임마다 해당 코드를 실행합니다(시스템처럼). 예를 들어, `PlayerEntity` 의 값을 확인하여 스크립트에서 동작을 트리거합니다.

다음 코드는 게임의 매 프레임마다 로그를 출력하며, `PlayerEntity` 이 이전에 정의한 `numericVariable`보다 클 때

```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://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-07e4722b53743d2bac04744175a46fc25488cc36%2Fupdate-script-logs.png?alt=media" alt="Update Method" data-size="line">

첫 번째 로그는 start() 메서드에 속하며, numericVariable을 설정했음을 나타냅니다. 두 번째 것은 update() 메서드에 속하며, 플레이어가 그 값보다 높을 때 출력됩니다.

## Creator Hub에 동작 노출하기

다음 유형의 `액션` 을 Script Component 스크립트 안에서 정의하고 Creator Hub의 UI에서 접근 가능하게 만들 수 있습니다. 이를 통해 이 `액션` 를 다른 엔티티와 함께 트리거할 수 있습니다.

```ts
  /**
   * 이 동작을 트리거할 수 있도록 노출
   * @action
   */
  exposedAction(creatorHubParameter: number) {
    console.log("Triggered from another entity using parameter: ", this.creatorHubParameter);
  }
```

`creatorHubParameter` 는 `액션` 매개변수로 노출되어 사용자 지정 값을 가질 수 있습니다. Script Component를 새로고침하면 새 동작이 Actions 드롭다운의 옵션으로 표시됩니다.

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-d7b71673260d80622c4b5635526aa3444d84ccff%2Fscript-component-action.png?alt=media\&token=0bedbaf4-0eac-4548-a2fa-400b2d2de668)

Action을 추가한 후에는 Creator Hub의 어떤 엔티티든 다음을 사용하여 이를 트리거할 수 있습니다. `트리거`

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-33aa38670114e43b0bb1beb493e2233642530167%2Fscript-component-action-trigger.png?alt=media\&token=acb49d50-040f-4215-81fd-f251f604fee6)

{% hint style="info" %}
**📔 참고**: Script 안에 필요한 만큼 Action을 추가할 수 있습니다. 이 모든 항목은 `액션` 드롭다운과는 독립적으로 접근할 수 있습니다.
{% endhint %}

## 외부에서 Script 메서드 호출하기

다른 Script 또는 `src/index.ts`에서 Script 메서드를 호출하려면 다음 단계를 따라야 합니다:

1. 만드세요 `public` 메서드는 Script 클래스 내부에 있습니다.
2. 다음을 실행하세요 `npm run build` 장면의 루트 디렉터리에서.
3. 공개 메서드를 사용하려는 파일에서 다음을 추가하세요. `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` 함수는 `Entity` 를 찾습니다. 그다음, `Entity` 가 존재하면, `callScriptMethod` 는 다음 매개변수와 함께 호출됩니다:

1. `엔티티`: `Entity` 다음을 가진 `public` 메서드.
2. `scriptPath`: `path` 에서 `Script` 클래스가 위치하는지.
3. `methodName`: 호출할 `public` 메서드의 이름.
4. `...args`: 메서드의 인자입니다. 이 경우 두 개가 있습니다. 순서대로, 하나씩 추가해야 합니다.

셋째, 정의된 `callScriptMethod`를 호출합니다. 이 경우, `scriptMethod`.

매개변수 값이 주어지면 출력은 다음과 같습니다:

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-32c18509225406a1f8162b0d9719fc1e38ed8da0%2Fscript-component-public-method.png?alt=media\&token=c0876cd3-198e-4530-8ca6-1edfcb3cca7c)

{% hint style="info" %}
**📔 참고**: 같은 논리로 `public` 다른 스크립트나 파일에서 Script 메서드를 호출할 수 있습니다. 이를 사용하여 `public` Script 클래스의 변수에서 값을 가져오거나 변경할 수 있습니다.
{% endhint %}

## 스크립트에서 다른 엔티티의 Action 트리거하기

유형의 매개변수를 사용하는 것이 가능합니다. `ActionCallback` Script 클래스 생성자에 `Entity`의 `액션` Creator Hub UI를 통해 정의된 것을 Script의 메서드에서 트리거할 수 있습니다.

이 예에서는 `anotherEntityAction` 가 `public` 파라미터를 설정하여 이미지 파일을 머티리얼의 텍스처로 지정하세요.

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

선택 가능한 `Entity` 과 `액션` 은 이제 Creator Hub UI에서 Script Component가 새로고침될 때 사용할 수 있습니다. `구체` 는 장면에 이미 존재하는 엔티티이며, 다음이라는 작업을 가지고 있습니다. `스케일`.

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-a264fa3fe8ceb754877b1022f0c653d3cb29ece6%2Fscript-component-action-callback.png?alt=media\&token=70b7820e-4093-4e84-92a1-9b25aedf1a02)

다른 엔티티의 Action은 이제 Script 클래스에서 접근할 수 있습니다. 다양한 방식으로 사용할 수 있습니다. 다음 예에서는 E 키를 누르면 다음이 트리거됩니다. `this.anotherEntityAction` 다음을 정의하여 `pointerEventsSystem` 에서 `start` 메서드.

```ts
  start() {
    pointerEventsSystem.onPointerDown(
      {
        entity: this.entity,
        opts: {
          button: InputAction.IA_PRIMARY,
          hoverText: "Press E to trigger an Action from another Entity.",
        },
      },
      () => {
        this.anotherEntityAction();
      }
    );
  }
```

### 선택 사항인 Action 콜백

하나의 `ActionCallback` 작성자가 연결하지 않은 매개변수는 `undefined`이며, 그 유형은 `ActionCallback | undefined`입니다. 호출하기 전에 확인하여 Action이 연결되었는지 여부와 관계없이 스크립트가 작동하도록 하세요:

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

{% hint style="info" %}
**📔 참고**: 노출과 트리거 결합하기 `동작` 는 매우 강력한 도구입니다. 한 엔티티에 Script Component를 정의하고, `public` 메서드를 사용해 Action을 노출한 다음, `ActionCallback` 파라미터를 설정하여 이미지 파일을 머티리얼의 텍스처로 지정하세요.
{% endhint %}

## 또한 참조하세요

* [스마트 아이템 - 기본](/creator/content-creator-ko/scene-editor/interactivity/smart-items.md)
* [스마트 아이템 - 고급](/creator/content-creator-ko/scene-editor/interactivity/smart-items-advanced.md)
* [상태와 조건](/creator/content-creator-ko/scene-editor/interactivity/states-and-conditions.md)
* [모든 항목을 스마트 아이템으로 만들기](/creator/content-creator-ko/scene-editor/interactivity/make-any-item-smart.md)
* [SDK 빠른 시작](/creator/content-creator-ko/sdk7/getting-started/sdk-101.md): 빠른 실전 입문을 위해 이 짧은 튜토리얼을 따라 하세요.
* [개발 워크플로](/creator/content-creator-ko/sdk7/getting-started/dev-workflow.md): 장면 생성 과정을 처음부터 끝까지 이해하려면 이것을 읽어보세요.
* [예시](https://studios.decentraland.org/resources?sdk_version=SDK7): 작업 예제 장면을 바로 살펴보세요.


---

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