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

# UI dinámica

Aprende cómo hacer que las UIs sean dinámicas y respondan a cambios en los datos.

Puedes definir una UI que incluya elementos dinámicos que se actualizan en cada tick. Solo tienes que actualizar la variable que representa estos datos, y la UI se adaptará a los nuevos valores.

Esto resulta muy útil para incluir elementos como un temporizador, la puntuación de un jugador, etc. Pero puedes ir un paso más allá y definir estructuras de UI completas basadas en el estado.

## Variables de referencia

Puedes hacer referencia a una variable en cualquier propiedad de uno de los componentes de una uiEntity. A medida que cambia el valor de la variable, la UI se adapta en consecuencia.

El ejemplo siguiente define una variable `playerCurrentPosition` y hace referencia a ella como parte de una cadena en un componente `uiText` . Luego, un sistema actualiza el valor de esta variable en cada tick usando la posición actual del jugador. A medida que cambia el valor de la variable, la UI se actualiza en consecuencia, sin que sea necesario modificarla explícitamente.

***archivo ui.tsx:***

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

// dibujar 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) }}
  />
)
```

***archivo 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)} }`
})
```

En el ejemplo anterior, también podrías incluir la variable como parte de la cadena, envolviéndola en `${ }`.

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

## Llamar a funciones desde una UI

También puedes llamar a una función desde una definición JSX para que devuelva un valor que se use en una propiedad de la UI. Las funciones llamadas desde esta definición JSX se ejecutan repetidamente en cada tick del bucle del juego.

En el ejemplo siguiente, un componente `uiText` llama a la función `getPlayerPosition()` para definir parte de la cadena que se mostrará.

Este ejemplo es similar al de la sección anterior, pero al llamar a una función desde dentro de la definición de la UI evitamos declarar una variable independiente y definir un sistema para modificarla. Ten en cuenta que `getPlayerPosition()` se llama en cada tick del bucle del juego, sin necesidad de declarar explícitamente un sistema.

***archivo 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)} }`
}
```

***archivo index.ts:***

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

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

## Mostrar y ocultar una UI

La forma más sencilla de mostrar y ocultar una UI es usar una variable para el valor de la propiedad `display` en el componente `uiTransform`de una entidad. La propiedad `display` hace que una entidad de UI y todos sus elementos secundarios sean invisibles si se establece en `none`.

El ejemplo siguiente usa una variable para establecer el campo `display` de una parte de la UI. El valor de esta variable se puede alternar al hacer clic en otro elemento de la UI.

***archivo 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>
      {/* Menú */}
      <UiEntity
       uiTransform={{
          width: '80%',
          height: '100px',
          alignContent: 'center',
          justifyContent: 'center',
          display: isMenuVisible ? 'flex': 'none'
        }}
         uiText={{
          value: "Menú",
          fontSize: 30
        }}
        uiBackground={{ color: Color4.Green() }}
      />
      {/* botón */}
      <UiEntity
        uiTransform={{
          width: 100,
          height: 30,
          margin: { top: '35px', left: '500px' }
        }}
        uiText={{
          value: "Alternar menú",
          fontSize: 40
        }}
        uiBackground={{ color: Color4.Red() }}
        onMouseDown={toggleMenuVisibility}
      />
   </UiEntity>
)
```

***archivo index.ts:***

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

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

## Entidades de UI dinámicas

Los ejemplos de las secciones anteriores muestran cómo cambiar dinámicamente una sola propiedad de una entidad, pero también puedes definir estructuras completas de entidades que se adapten a los cambios dinámicos de los datos. Este tipo de patrón es habitual en el desarrollo web cuando se usan bibliotecas como React y es muy potente. Con él puedes definir aplicaciones de UI muy flexibles y escalables.

El siguiente ejemplo muestra los ID de todas las entidades de la escena que tienen un `MeshRenderer` y `Transform`. Crea un `uiText` para cada una. A medida que cambia el contenido de la escena, la lista de entidades de UI también se adapta en cada tick.

***archivo 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 } }}
  />
}
```

***archivo 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-es/scenes-sdk7/ui-2d/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.
