> 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/2d-ui/dynamic-ui.md).

# 동적 UI

데이터 변경에 반응하는 동적 UI를 만드는 방법을 알아봅니다.

매 틱마다 업데이트되는 동적 요소가 포함된 UI를 정의할 수 있습니다. 데이터에 해당하는 변수를 업데이트하기만 하면 새 값에 맞춰 UI가 변경됩니다.

타이머나 플레이어 점수 같은 요소를 포함할 때 매우 유용합니다. 더 나아가 상태에 따라 UI 구조 전체를 정의할 수도 있습니다.

## 변수 참조

uiEntity의 구성 요소 중 하나에서 어떤 속성이든 변수 하나를 간단히 참조할 수 있습니다. 변수 값이 바뀌면 UI도 그에 맞게 변경됩니다.

아래 예제에서는 변수 `playerCurrentPosition` 를 정의하고 이를 `uiText` 구성 요소의 문자열 일부로 참조합니다. 그런 다음 시스템이 매 틱마다 플레이어의 현재 위치를 사용해 이 변수의 값을 업데이트합니다. 변수 값이 바뀌면 UI도 그에 맞게 업데이트되므로 UI를 직접 수정할 필요가 없습니다.

***ui.tsx 파일:***

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { playerCurrentPosition } from './index'
import { Color4 } from '@dcl/sdk/math'

// draw UI
export const uiMenu = () => (
  <UiEntity
    uiTransform={{
			width: '100%',
			height: '100px',
			justifyContent: 'center',
			alignItems: 'center',
    }}
    uiText={{ value: `Player: `+  playerCurrentPosition, fontSize: 40 }}
    uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
  />
)
```

***index.ts 파일:***

```ts
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { engine, Transform } from '@dcl/sdk/ecs'
import { uiMenu } from './ui'

export function main() {
    ReactEcsRenderer.setUiRenderer(uiMenu, { virtualWidth: 1920, virtualHeight: 1080 })
}

// define variable
export let playerCurrentPosition: string = ""

// system to update variable
engine.addSystem(() => {
  const playerPosition = Transform.getOrNull(engine.PlayerEntity)
  if (!playerPosition) return
  const { x, y, z } = playerPosition.position
  playerCurrentPosition =  `{x: ${x.toFixed(2)}, y: ${y.toFixed(2)}, z: ${z.toFixed(2)} }`
})
```

위 예제에서는 변수를 `${ }`.

```ts
uiText={{
	value: `Player: ${playerCurrentPosition}`,
	fontSize: 40
}}
```

## UI 내부에서 함수 호출하기

JSX 정의 안에서 함수를 호출해 UI 속성에 사용할 값을 반환할 수도 있습니다. 이 JSX 정의 안에서 호출되는 함수는 게임 루프의 매 틱마다 반복해서 호출됩니다.

아래 예제에서는 `uiText` 구성 요소가 `getPlayerPosition()` 함수를 호출해 표시할 문자열의 일부를 정의합니다.

이 예제는 이전 섹션의 예제와 비슷하지만, UI 정의 내부에서 함수를 호출하면 별도의 변수를 선언하고 해당 변수를 변경하는 시스템을 정의할 필요가 없습니다. 참고로 `getPlayerPosition()` 은 별도의 시스템을 명시적으로 선언하지 않아도 게임 루프의 매 틱마다 호출됩니다.

***ui.tsx 파일:***

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'
import { engine, Transform } from "@dcl/sdk/ecs";

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: '100%',
      height: '100px',
      justifyContent: 'center',
      alignItems: 'center',
    }}
    uiText={{ value: `Player: `+  getPlayerPosition(), fontSize: 40 }}
    uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
  />
)

function getPlayerPosition(){
  const playerPosition = Transform.getOrNull(engine.PlayerEntity)
  if (!playerPosition) return 'loading...'
  const { x, y, z } = playerPosition.position
  return `{x: ${x.toFixed(2)}, y: ${y.toFixed(2)}, z: ${z.toFixed(2)} }`
}
```

***index.ts 파일:***

```ts
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
    ReactEcsRenderer.setUiRenderer(uiMenu, { virtualWidth: 1920, virtualHeight: 1080 })
}
```

## UI 표시 및 숨기기

UI를 표시하거나 숨기는 가장 간단한 방법은 엔티티의 `display` 속성 값에 변수를 사용하는 것입니다. `uiTransform`의 `display` 속성을 `none`.

다음 예제에서는 변수를 사용해 UI 일부의 `display` 필드 값을 설정합니다. 다른 UI 요소를 클릭하면 이 변수 값을 전환할 수 있습니다.

***ui.tsx 파일:***

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

// Variable to reflect current state of menu visibility
var isMenuVisible: boolean = false

// Function to toggle the state of the menu
function toggleMenuVisibility() {
  isMenuVisible = !isMenuVisible
}

export const uiMenu = () => (
   // parent
   <UiEntity>
      {/* 메뉴 */}
      <UiEntity
       uiTransform={{
          width: '80%',
          height: '100px',
          alignContent: 'center',
          justifyContent: 'center',
          display: isMenuVisible ? 'flex': 'none'
        }}
         uiText={{
          value: "메뉴",
          fontSize: 30
        }}
        uiBackground={{ color: Color4.Green() }}
      />
      {/* 버튼 */}
      <UiEntity
        uiTransform={{
          width: 100,
          height: 30,
          margin: { top: '35px', left: '500px' }
        }}
        uiText={{
          value: "메뉴 전환",
          fontSize: 40
        }}
        uiBackground={{ color: Color4.Red() }}
        onMouseDown={toggleMenuVisibility}
      />
   </UiEntity>
)
```

***index.ts 파일:***

```ts
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
    ReactEcsRenderer.setUiRenderer(uiMenu, { virtualWidth: 1920, virtualHeight: 1080 })
}
```

## 동적 UI 엔터티

위 섹션의 예제에서는 엔터티의 단일 속성을 동적으로 변경하는 방법을 보여 줍니다. 하지만 동적으로 변하는 데이터를 기반으로 확장할 수 있는 엔터티 전체 구조를 정의할 수도 있습니다. React와 같은 라이브러리를 사용하는 웹 개발에서 흔히 볼 수 있는 이 패턴은 매우 강력합니다. 이를 통해 유연하고 확장성이 뛰어난 UI 애플리케이션을 정의할 수 있습니다.

다음 예제는 씬에 있는 모든 엔터티 중 `MeshRenderer` 및 `Transform`을 가진 엔터티의 ID를 나열합니다. 각 엔터티에 대해 `uiText` 를 생성합니다. 씬의 콘텐츠가 변경되면 UI 엔터티 목록도 매 틱마다 이에 맞춰 갱신됩니다.

***ui.tsx 파일:***

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'
import { engine } from '@dcl/sdk/ecs'
import { MeshRenderer } from '@dcl/sdk/ecs'
import { Transform } from '@dcl/sdk/ecs'

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: '100%',
      height: '300px',
      justifyContent: 'center',
      alignItems: 'center',
    }}
    uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
  >
    <UiEntity>
      {generateText()}
    </UiEntity>
  </UiEntity>
)


function generateText(){
  return Array.from(engine.getEntitiesWith(
    MeshRenderer,
    Transform
  )).map(([entity]) => <TextComponent value={entity.toString()} key={entity} /> )
}


function TextComponent(props: { value: string; key: string | number }) {
  return <UiEntity
    key={props.key}
    uiTransform={{ width: 80, height: 20 }}
    uiText={{ value: props.value, textAlign: 'middle-center', fontSize: 12 }}
    uiBackground={{ color: { r: 1, g: 0.176, b: 0.333, a: 1 } }}
  />
}
```

***index.ts 파일:***

```ts
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
    ReactEcsRenderer.setUiRenderer(uiMenu, { virtualWidth: 1920, virtualHeight: 1080 })
}
```


---

# 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/2d-ui/dynamic-ui.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.
