> 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/sdk7/architecture/custom-components.md).

# 사용자 지정 컴포넌트

엔티티와 관련된 특정 데이터를 처리할 사용자 지정 컴포넌트를 만듭니다

엔티티에 관한 데이터는 [컴포넌트](/creator/content-creator-ko/sdk7/architecture/entities-components.md)에 저장됩니다. Decentraland SDK는 엔티티의 위치, 모양, 재질 등 다양한 측면을 관리하는 기본 컴포넌트들을 제공합니다. 엔진은 이러한 컴포넌트의 정보를 해석하여 값이 변경되는 즉시 그에 따라 엔티티 렌더링 방식을 변경합니다.

씬의 로직에서 SDK의 기본 컴포넌트로 처리되지 않는 엔티티 정보를 저장해야 한다면, 씬에 사용자 지정 컴포넌트 유형을 만들 수 있습니다. 그런 다음 이 컴포넌트의 변경 사항을 확인하고 이에 따라 대응하는 [시스템](/creator/content-creator-ko/sdk7/architecture/systems.md) 을 만들 수 있습니다.

## 컴포넌트 정의

새 컴포넌트를 정의하려면 `engine.defineComponent`를 사용합니다. 각 컴포넌트에는 다음 항목이 필요합니다.

* &#x20;**componentName**: SDK가 이 컴포넌트 유형을 식별하기 위해 내부적으로 사용하는 고유한 문자열 식별자입니다. 고유하기만 하면 어떤 문자열이든 사용할 수 있습니다.
* &#x20;**schema**: 컴포넌트가 보유하는 데이터 구조를 정의하는 클래스입니다.
* **기본값** *(선택 사항)*: 기본값이 제공되지 않았을 때 컴포넌트 복사본을 초기화하는 데 사용할 기본값이 포함된 객체입니다.

```ts
export const WheelSpinComponent = engine.defineComponent('wheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})
```

{% hint style="warning" %}
**📔 참고**: 사용자 지정 컴포넌트는 항상 별도의 파일에서 `main()` 함수 바깥에 작성해야 합니다. 해당 함수가 실행되기 전에 컴포넌트가 해석되어야 합니다. 권장 위치는 `main()` 입니다. 컴포넌트마다 별도의 파일을 만들어 `/components` 폴더에 넣고, 이 폴더를 `/src`안에 배치하세요. 이렇게 하면 향후 프로젝트에서 컴포넌트를 더 쉽게 재사용할 수 있습니다.
{% endhint %}

사용자 지정 컴포넌트를 정의한 뒤에는 씬의 엔티티를 참조하는 해당 컴포넌트의 인스턴스를 만들 수 있습니다. 컴포넌트 인스턴스를 만들 때는 컴포넌트 스키마의 각 필드에 값을 지정합니다. 값은 각 필드에 선언된 유형과 일치해야 합니다.

```ts
// 엔티티 생성
const wheel1 = engine.addEntity()
const wheel2 = engine.addEntity()

// 컴포넌트 인스턴스 만들기
WheelSpinComponent.create(wheel1, {
	spinning: true,
	speed: 10,
})

WheelSpinComponent.create(wheel2, {
	spinning: false,
	speed: 0,
})
```

컴포넌트가 추가된 각 엔티티에는 해당 엔티티의 특정 데이터를 담는 컴포넌트 복사본이 새로 생성됩니다.

사용자 지정 컴포넌트에서도 다른 컴포넌트에서 사용할 수 있는 일반적인 함수를 사용할 수 있습니다.

```ts
// 엔티티에서 컴포넌트의 읽기 전용 인스턴스 가져오기
const readOnlyInstance = MyCustomComponent.get(myEntity)

// 엔티티에서 컴포넌트의 수정 가능한 인스턴스 가져오기
const mutableInstance = MyCustomComponent.getMutable(myEntity)

// 엔티티의 컴포넌트 인스턴스 삭제하기
MyCustomComponent.deleteFrom(myEntity)
```

## componentName 설명

각 컴포넌트에는 내부적으로 컴포넌트를 구별하는 고유한 이름 또는 식별자가 있어야 합니다. 코드의 다른 부분에서 이 내부 식별자를 사용할 필요는 없습니다. 컴포넌트에 지정한 이름의 첫 글자만 소문자로 바꿔 식별자로 사용하는 것이 일반적인 방법이지만, 가장 중요한 점은 프로젝트 내에서 식별자가 고유해야 한다는 것입니다.

라이브러리의 일부로 공유할 컴포넌트를 만들 때는 라이브러리의 컴포넌트 이름이 해당 컴포넌트를 사용하는 프로젝트의 컴포넌트 이름이나 그 프로젝트에서 함께 사용하는 다른 라이브러리의 컴포넌트 이름과 겹치지 않도록 주의하세요. 이름이 겹칠 위험을 방지하려면 라이브러리 이름을 다음과 같이 `componentName` 문자열에 포함하는 것이 권장됩니다. 다음 형식을 사용할 수 있습니다. `${packageName}::${componentName}`. 예를 들어`MyUtilities` 라이브러리에 `MoveEntity` 컴포넌트를 포함한다면, 해당 컴포넌트의 `componentName` 를 다음과 같이 설정하세요. `MyUtilities::moveEntity`.

## 플래그로 사용하는 컴포넌트

데이터를 저장하지 않고 엔티티를 다른 엔티티와 구분하기 위한 표시만 하는 컴포넌트를 추가할 수 있습니다. 이렇게 하려면 스키마를 빈 객체로 두세요.

이는 [컴포넌트 쿼리](/creator/content-creator-ko/sdk7/architecture/querying-components.md)를 사용할 때 특히 유용합니다. 간단한 플래그 컴포넌트를 사용하면 엔티티를 서로 구분할 수 있으며, 시스템이 필요 이상으로 많은 엔티티를 순회하지 않도록 할 수 있습니다.

```ts
export const IsEnemyFlag = engine.defineComponent('isEnemyFlag', {})
```

그런 다음 이 컴포넌트가 있는 모든 엔티티를 순회하는 시스템을 만들 수 있습니다.

```ts
export function handleEnemies() {
	for (const [entity] of engine.getEntitiesWith(IsEnemyFlag)) {
		// 각 엔티티에 대해 작업 수행
	}
}

engine.addSystem(handleEnemies)
```

## 컴포넌트 스키마

스키마는 컴포넌트 내부 데이터의 구조를 설명합니다. 컴포넌트에는 원하는 만큼 필드를 저장할 수 있으며, 각 필드는 스키마 구조에 포함되어야 합니다. 스키마에는 필요한 만큼 여러 단계로 중첩된 항목을 포함할 수 있습니다.

스키마의 모든 필드에는 타입 선언이 있어야 합니다. SDK에서 제공하는 특수 스키마 타입만 사용할 수 있습니다. 예를 들어, `Schemas.Boolean` 을 `boolean`타입 대신 사용하세요.  `Schemas.` 를 입력하면 IDE에 사용 가능한 모든 옵션이 표시됩니다.

```ts
export const WheelSpinComponent = engine.defineComponent('WheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})
```

위 예시에서는 스키마에 두 개의 값, 즉 `spinning` 불리언과 `speed` 부동 소수점 숫자를 저장하는 컴포넌트를 정의합니다.

컴포넌트를 정의하면서 스키마를 인라인으로 작성하거나, 가독성을 높이기 위해 스키마를 별도로 만든 다음 참조할 수 있습니다.

```ts
// 옵션 1: 인라인 정의
export const WheelSpinComponent = engine.defineComponent('WheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})

// 옵션 2: 스키마와 컴포넌트를 별도로 정의

//// 스키마
const mySchema = {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
}

//// 컴포넌트
export const WheelSpinComponent = engine.defineComponent(
	'WheelSpinComponent',
	mySchema
)
```

{% hint style="info" %}
**💡 팁**: 컴포넌트 인스턴스를 만들 때 *Ctrl + Space*.
{% endhint %}

### 를 누르면 VS Studio 자동 완성 기능이 컴포넌트에 추가할 수 있는 필드를 제안합니다.

스키마의 필드에 사용할 수 있는 기본 유형은 다음과 같습니다.

* `Schemas.Boolean`
* `Schemas.Byte`
* `Schemas.Double`
* `Schemas.Float`
* `Schemas.Int`
* `Schemas.Int64`
* `Schemas.Number`
* `Schemas.Short`
* `Schemas.String`
* `Schemas.Entity`

다음과 같은 복합 유형도 있습니다. 각 유형에는 숫자 값을 포함하는 여러 중첩 속성이 있습니다.

* `Schemas.Vector3`
* `Schemas.Quaternion`
* `Schemas.Color3`
* `Schemas.Color4`

{% hint style="info" %}
**💡 팁**에 대한 자세한 내용은 [기하 유형](/creator/content-creator-ko/sdk7/3d/special-types.md) 및 [색상 유형](/creator/content-creator-ko/sdk7/3d/color-types.md) 을 참조하세요. 이러한 데이터 유형의 활용 방법을 확인할 수 있습니다.
{% endhint %}

예를 들어, 다음과 같이 컴포넌트에서 이러한 스키마 유형을 사용하면 엔티티의 점진적인 이동을 추적할 수 있습니다. 이 컴포넌트는 초기 위치와 최종 위치를 Vector3 값으로 저장하고, 속도와 이동 경로에서 완료된 부분의 비율을 float 숫자로 저장합니다. 예시의 전체 구현은 [엔티티 이동](/creator/content-creator-ko/sdk7/3d/move-entities.md#move-between-two-points) 을 참조하세요.

```ts
const MoveTransportData = {
	start: Schemas.Vector3,
	end: Schemas.Vector3,
	fraction: Schemas.Float,
	speed: Schemas.Float,
}

export const LerpTransformComponent = engine.defineComponent(
	'LerpTransformComponent',
	MoveTransportData
)
```

### 배열 유형

필드 유형을 배열로 설정하려면 `Schemas.Array()`를 사용하세요. 배열 요소의 유형을 인수로 전달합니다.

```ts
const MySchema = {
	numberList: Schemas.Array(Schemas.Int),
}
```

배열 필드를 `MyComponent.get()`으로 읽으면 배열은 읽기 전용입니다. 배열을 직접 변경하는 `.push()`와 같은 메서드는 사용할 수 없습니다. 내용을 변경해야 하는 경우 `MyComponent.getMutable()` 를 사용하세요.

### 선택적 필드

필드에 값 또는 `Schemas.Optional()` 를 사용하면 필드에 값이나 `undefined`.

```ts
const MySchema = {
	playerId: Schemas.Optional(Schemas.String),
	score: Schemas.Optional(Schemas.Int),
}
```

오직 `undefined` 만 "설정되지 않음"으로 간주됩니다. 다음과 같은 거짓 값은 `false`, `0`및 `''` 와 같이 작성된 그대로 저장되고 다시 읽힙니다.

### 중첩 스키마 유형

필드의 유형을 객체로 설정하려면 `Schemas.Map()`을 사용합니다. 이 객체의 내용을 속성으로 전달하세요. 이 중첩 객체는 기본적으로 부모 스키마 안에 중첩된 스키마입니다.

```ts
const MySchema = {
	simpleField: Schemas.Boolean,
	myComplexField: Schemas.Map({
		nestedField1: Schemas.Boolean,
		nestedField2: Schemas.Boolean,
	}),
}
```

가독성과 재사용성을 높이려면 중첩 스키마를 별도로 정의한 다음 부모 스키마를 정의할 때 참조하여 동일한 결과를 얻을 수도 있습니다.

```ts
const MyNestedSchema = Schemas.Map({
	nestedField1: Schemas.Boolean,
	nestedField2: Schemas.Boolean,
})

const MySchema = {
	simpleField: Schemas.Boolean,
	myComplexField: MyNestedSchema,
}
```

### 열거형 유형

스키마 필드의 유형을 열거형으로 설정할 수 있습니다. 열거형을 사용하면 유한한 수의 옵션 중에서 쉽게 선택할 수 있으며, 각 옵션에 사람이 읽기 쉬운 값을 지정할 수 있습니다.

필드 유형을 열거형으로 설정하려면 먼저 열거형을 정의해야 합니다. 그런 다음 열거형 유형에 따라 `Schemas.EnumNumber` 또는 `Schemas.EnumString`을 사용해 참조할 수 있습니다. 이 함수는 열거형과 해당 필드에 사용할 기본값, 두 개의 매개변수를 받습니다.

```ts
//// 문자열 열거형

// 열거형 정의
enum Color {
	Red = 'red',
	Green = 'green',
	Pink = 'pink',
}

// 이 열거형을 필드에서 사용하는 컴포넌트 정의
const ColorComponent = engine.defineComponent('Color', {
	color: Schemas.EnumString<Color>(Color, Color.Red),
})

// 엔티티에서 컴포넌트 사용
ColorComponent.create(engine.addEntity(), { color: Color.Green })

//// 숫자 열거형

// 열거형 정의
enum CurveType {
	LINEAR,
	EASEIN,
	EASEOUT,
}

// 이 열거형을 필드에서 사용하는 컴포넌트 정의
const CurveComponent = engine.defineComponent('curveComponent', {
	curve: Schemas.EnumNumber<CurveType>(CurveType, CurveType.LINEAR),
})

// 엔티티에서 컴포넌트 사용
CurveComponent.create(engine.addEntity(), { curve: CurveType.EASEIN })
```

### 상호 교환 가능한 유형

스키마 필드의 유형에 서로 다른 유형을 허용하는 `oneOf` 패턴을 따르도록 설정할 수 있습니다.

```ts
const MySchema = {
	myField: Schemas.OneOf({ type1: Schemas.Vector3, type2: Schemas.Quaternion }),
}

export const MyComponent = engine.defineComponent('MyComponent', MySchema)
```

컴포넌트 인스턴스를 생성할 때는 다음 예시처럼 `$case`를 사용해 선택한 유형을 지정해야 합니다.

```ts
MyComponent.create(myEntity, {
	myField: {
		$case: 'type1',
		value: Vector3.create(1, 1, 1),
	},
})
```

필드를 설정하지 않아도 유효합니다. 설정되지 않은 `OneOf` 필드에는 `$case` 가 없으며, 빈 객체로 읽힙니다. `{}`.

### 단일 타입의 컴포넌트

컴포넌트가 여러 필드로 구성된 객체를 보유해야 하는 것은 아닙니다. 단일 값을 보유하는 컴포넌트를 정의하려면 다음을 사용하세요. `engine.defineComponentFromSchema()` 그리고 타입을 직접 전달하세요:

```ts
// 엔티티마다 숫자 하나를 보유하는 컴포넌트
export const Score = engine.defineComponentFromSchema('my-scene::Score', Schemas.Int)

// 엔티티별 숫자 목록을 저장하는 컴포넌트
export const History = engine.defineComponentFromSchema(
	'my-scene::History',
	Schemas.Array(Schemas.Int)
)
```

저장된 값이 falsy인 경우에도 다른 컴포넌트와 동일하게 동작합니다.  `Score` 은 `0` 존재하며 다음 값을 보유하는 컴포넌트입니다:  `0`, 누락된 컴포넌트가 아닙니다.

## 기본값

컴포넌트에 기본값을 설정하면 새 복사본을 만들 때마다 모든 값을 명시적으로 설정할 필요가 없으므로 유용합니다.

이 `engine.defineComponent()` 함수는 세 번째 인자로 기본값으로 사용할 값이 담긴 객체를 받습니다. 이 객체에는 스키마에 정의된 값의 일부 또는 전부를 포함할 수 있습니다. 기본값이나 컴포넌트 복사본을 초기화할 때 제공하는 값에 포함되지 않은 필드는 타입에 따라 `0`, `false` 또는 빈 문자열과 같이 0에 가까운 값으로 초기화됩니다.

```ts
// 정의

//// 스키마
const mySchema = {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
}

//// 기본값
const myDefaultValues = {
	spinning: true,
	속도: 1,
}

//// 컴포넌트
export const WheelSpinComponent = engine.defineComponent(
	'WheelSpinComponent',
	mySchema,
	myDefaultValues
)

// 사용법
export function main() {
	//// 엔터티 생성
	const wheel = engine.addEntity()
	const wheel2 = engine.addEntity()

	//// 기본값으로 컴포넌트 초기화
	WheelSpinComponent.create(wheel)

	//// 사용자 지정 값 하나로 컴포넌트 초기화하고, 나머지는 기본값 사용
	WheelSpinComponent.create(wheel2, { speed: 5 })
}
```

위 예제에서는 다음을 생성합니다 `WheelSpinComponent` 스키마와 사용할 기본값 집합을 모두 포함하는 컴포넌트입니다. 값을 지정하지 않고 이 컴포넌트의 복사본을 초기화하면 기본값으로 설정된 값이 사용됩니다.

## 변경 사항 구독

일반적인 사용 사례는 특정 컴포넌트의 데이터가 변경될 때만 함수를 실행하는 것입니다. 다음을 사용하면 [OnChange](/creator/content-creator-ko/sdk7/architecture/subscribe-to-changes.md) 시스템을 정의하거나 이전 값과 새 값을 명시적으로 비교할 필요 없이 함수를 실행할 수 있습니다.

```ts
export function main() {
	//엔티티 생성 등

	WheelSpinComponent.onChange(myEntity, (componentData) => {
		if (!componentData) return
		console.log(componentData.speed)
		console.log(componentData.spinning)
	})
}
```

## 컴포넌트를 사용하는 시스템 만들기

컴포넌트를 정의하고 장면의 엔티티에 추가했다면 [시스템](/creator/content-creator-ko/sdk7/architecture/systems.md) 이 컴포넌트에 저장된 데이터를 사용해 로직을 수행합니다.

```ts
// 컴포넌트 정의
export const WheelSpinComponent = engine.defineComponent('WheelSpinComponent', {
	spinning: Schemas.Boolean,
	speed: Schemas.Float,
})

// 사용법
export function main() {
	// 엔티티 생성
	const wheel1 = engine.addEntity()
	const wheel2 = engine.addEntity()

	// 컴포넌트 인스턴스 만들기
	WheelSpinComponent.create(wheel1, {
		spinning: true,
		speed: 10,
	})

	WheelSpinComponent.create(wheel2, {
		spinning: false,
		speed: 0,
	})
}

// 이러한 엔티티를 순회하는 시스템 정의
export function spinSystem(dt: number) {
	// WheelSpinComponent가 있는 모든 엔티티 순회
	for (const [entity, wheelSpin] of engine.getEntitiesWith(
		WheelSpinComponent
	)) {
		// spinning == true인 경우에만 작업 수행
		if (wheelSpin.spinning) {
			// 변경 가능한 Transform 컴포넌트를 가져옵니다
			const transform = Transform.getMutable(entity)

			// 회전 값을 적절히 업데이트
			transform.rotation = Quaternion.multiply(
				transform.rotation,
				Quaternion.fromAngleAxis(dt * wheelSpin.speed, Vector3.Up())
			)
		}
	}
}

// 엔진에 시스템 추가
engine.addSystem(spinSystem)
```

위 예제에서는 사용자 지정  `wheelSpinComponent`를 포함하는 모든 엔티티를 순회하며 게임 루프가 실행될 때마다 약간씩 회전시키는 시스템을 정의합니다. 이 회전량은 각 엔티티의 컴포넌트 인스턴스에 저장된  `speed`  값에 비례합니다. 이 예제에서는 관련 엔티티만 가져오기 위해  [컴포넌트 쿼리](/creator/content-creator-ko/sdk7/architecture/querying-components.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-ko/sdk7/architecture/custom-components.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.
