> 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 Component를 사용하면, 엔티티 자체 내부에서 사용자 지정 코드를 실행하는 엔티티를 만들 수 있습니다.

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

## Script Component 설정

1. 다음을 클릭하여 엔티티에 Script Component를 추가하세요. `+` 버튼을 클릭하고 선택합니다. 다음을 클릭하여 새 Script를 만듭니다. **+ 새 Script 모듈 추가** 를 선택한 다음 이름을 지정하거나, 파일 경로를 사용합니다(기존 파일을 찾아보기 또는 드래그 앤 드롭).

![](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)

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,     // DO NOT REMOVE
    public entity: Entity,   // DO NOT REMOVE
    // 아래에 사용자 지정 입력을 추가하세요
  ) {}

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

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

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

* 그 **constructor**,
* 그 **start()** 메서드
* 그 **update()** 메서드.

## 생성자

생성자에는 Creator Hub에서 씬으로부터 동적으로 노출하고 수정하려는 매개변수가 포함됩니다.

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

파일이 저장되면, **새로고침** 버튼을 누르면 Script Component에서 모든 변경 사항이 업데이트됩니다.

<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)

## 매개변수

다른 엔티티가 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에 노출됩니다. The `private` 키워드는 `BuildingScript` 클래스 내부에서의 접근만 제한합니다. 자세한 내용은 TypeScript 공식 문서의\
[매개변수 속성](https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties).
{% endhint %}

### Script 내부에서 매개변수에 접근하기

코드에서 매개변수 값을 접근하려면 다음 표기를 사용합니다. `this.definedParameter`. 예를 들어, `this.numericVariable` 또는 `this.entity`.

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

`console.log("엔티티용 BuildingScript가 초기화되었습니다:", this.entity);`.

생성자에서 정의한 값의 값을 로그하려면 다음과 같이 변경하세요:

`console.log("BuildingScript가 numericVariable과 함께 초기화되었습니다:",`, `this.numericVariable);`

Creator Hub UI에서 매개변수 값을 변경하면, 이 로그 값도 그에 따라 반영되는 것을 볼 수 있습니다.

### 기본 매개변수

생성자에는 기본적으로 `src` 그리고 하나의 `entity` 매개변수가 포함되어 있으며, 이는 스크립트 코드에 매우 유용합니다:

* `this.entity` 항상 해당 `스크립트` 컴포넌트를 가진 엔티티를 가리킵니다. 이를 사용해 엔티티에 대한 정보를 액세스하거나 컴포넌트를 추가하세요.
* `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)

그 **update()** 한편, 메서드는 게임의 매 프레임마다 코드가 실행됩니다(Systems처럼). 예를 들어, 스크립트에서 동작을 트리거하기 위해 `PlayerEntity` 의 값을 확인합니다.

다음 코드는 게임의 매 프레임마다 로그를 출력합니다. `PlayerEntity` 이 이전에 정의한 `numericVariable`보다 큰 경우,

```ts
update(dt: number) {
    if (Transform.get(engine.PlayerEntity).position.y > this.numericVariable ) {
      console.log("플레이어의 높이가 ", 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에 액션 노출하기

다음과 같은 `Action` 를 Script Component 스크립트 안에 정의하고 Creator Hub UI에서 접근 가능하게 할 수 있습니다. 이렇게 하면 이 `Action` 를 다른 엔티티와 함께 트리거할 수 있습니다.

```ts
  /**
   * 이 액션을 트리거 가능하도록 노출
   * @action
   */
  exposedAction(creatorHubParameter: number) {
    console.log("다른 엔티티에서 파라미터를 사용해 트리거됨: ", this.creatorHubParameter);
  }
```

`creatorHubParameter` 다음으로 노출됩니다. `Action` 매개변수로 노출되어 사용자 지정 값을 줄 수 있습니다. 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)

액션을 추가한 후에는 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)

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

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

다른 Script 또는 `src/index.ts`에서 Script 메서드를 호출하려면 다음 단계를 따르세요:

1. 생성하세요 `public` 메서드를 Script 클래스 안에 둡니다.
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("true 매개변수와 함께 public 메서드가 호출되었습니다!: ", someNumberParameter);
    } else {
      console.log("false 매개변수와 함께 public 메서드가 호출되었습니다!", 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`: `Entity` 를 가진 `public` 메서드.
2. `scriptPath`: `경로` 가 위치한 `스크립트` 클래스.
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)

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

## Script에서 다른 엔티티의 액션 트리거하기

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

이 예제에서, `anotherEntityAction` 가 다음으로 추가됩니다: `public` 매개변수.

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

선택 가능한 `Entity` 및 `Action` 는 이제 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)

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

```ts
  start() {
    pointerEventsSystem.onPointerDown(
      {
        entity: this.entity,
        opts: {
          button: InputAction.IA_PRIMARY,
          hoverText: "다른 엔티티의 액션을 트리거하려면 E를 누르세요.",
        },
      },
      () => {
        this.anotherEntityAction();
      }
    );
  }
```

### 선택적 액션 콜백

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

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

{% hint style="info" %}
**📔 참고**: 노출과 트리거를 결합하기 `동작` 은 매우 강력한 도구입니다. 한 엔티티에 Script Component를 정의하고, `public` 메서드를 사용해 액션을 노출한 다음, 다른 엔티티의 Script Component에서 `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 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-ko/scene-editor/extend-with-code/script-component.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.
