> 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-zh/chang-jing-sdk7/jiao-hu-xing/runtime-data.md).

# 运行时数据

从场景运行所在的上下文以及场景本身获取数据。

## 获取 Decentraland 时间

Decentraland 遵循昼夜循环，每个循环需要 2 小时，因此每天会完成 12 个完整循环。玩家也可以更改设置，体验一天中特定的固定时刻，例如始终看到 Decentraland 中晚上 10 点的夜空。因此，不同玩家所处的 Decentraland 时间可能有所不同。

使用 `getWorldTime()` 获取玩家在 Decentraland 中体验到的时刻。

```ts
import { getWorldTime } from '~system/Runtime'

executeTask(async () => {
  let time = await getWorldTime({})
  console.log(time.seconds)
})
```

{% hint style="info" %}
**💡 提示**： `getWorldTime()` 函数是异步的。如果你不熟悉异步函数，请参阅 [异步函数](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md) 。
{% endhint %}

`getWorldTime()` 会返回一个包含 `seconds` 属性的对象。该属性表示从一天开始到现在经过了多少秒（按 Decentraland 时间计算），并假设完整周期持续 24 小时。将秒数除以 60 可得到分钟，再除以 60 可得到从一天开始经过的小时数。例如，如果 `seconds` 值为 *36000*，则对应 *上午 10 点*.

在 Decentraland 时间中，太阳总是在 6:15 升起，并在 19:50 落下。

你可以利用这些信息相应地调整场景，例如在白天播放鸟鸣声、天黑时播放蟋蟀声，或者在天黑时启用路灯的自发光材质。

```ts
import { getWorldTime } from '~system/Runtime'

executeTask(async () => {
  let time = await getWorldTime({})
  console.log(time.seconds)
  if (time.seconds < 6.25 * 60 * 60 || time.seconds > 19.85 * 60 * 60) {
    // 夜间
    console.log('playing cricket sounds')
  } else {
    // 白天
    console.log('playing bird sounds')
  }
})
```

## 获取 Realm 数据

Decentraland 中的玩家分布在多个独立的 *Realm*中。不同 Realm 中的玩家无法看到彼此、互动或聊天，即使他们站在同一地块上也是如此。以这种方式划分玩家，可以让 Decentraland 容纳数量不受限制的玩家，而不会遇到任何限制。此外，系统还会将位于相近区域的玩家配对，以确保进行互动的玩家之间拥有可接受的 ping 延迟。

如果你的场景会向 [第三方服务器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/third-party-servers.md) 发送数据，以便在玩家之间实时同步更改，那么通常应确保只在同一 Realm 中的玩家之间同步更改。属于一个 Realm 的所有更改都应与其他 Realm 中的更改分开处理。否则，玩家会看到事物诡异地发生变化，却没有人进行更改。

```ts
import { getRealm } from '~system/Runtime'

executeTask(async () => {
  const { realmInfo } = await getRealm({})
  if (!realmInfo) return
  console.log(`你所在的 Realm：`, realmInfo.realmName)
})
```

{% hint style="info" %}
**💡 提示**： `getRealm()` 函数是异步的。如果你不熟悉异步函数，请参阅 [异步函数](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md) 。
{% endhint %}

Decentraland 通过一个去中心化的通信服务器网络处理玩家之间的通信（包括玩家位置、聊天、messageBus 消息和智能物品状态更改）。其中每台服务器都称为一个 **Realm**。每台服务器都可以支持多个独立的 **房间** （也称为 **个岛屿**），每个房间都将 Decentraland 地图上彼此靠近的一组玩家分到一起。

getRealm() `getRealm()` 函数会返回以下信息：

* `baseUrl`: *（字符串）* realm 服务器的域名
* `realmName`: *（字符串）* realm 服务器的名称
* `networkId`: *（数字）* 以太坊网络
* `commsAdapter`: *（字符串）* 通信适配器，移除所有查询参数（凭据）
* `isPreview`: *（布尔值）* 如果场景以本地预览模式运行，而非发布在 Decentraland 上，则为 true。
* `isConnectedSceneRoom`: *（布尔值）* 如果用户已连接到场景房间，则为 true。

{% hint style="warning" %}
**📔 注意**： `layer` 属性已弃用，应避免使用。
{% endhint %}

玩家在地图上移动时，可能会切换房间，以便与此时离他们最近的玩家分到一起。房间也会动态调整边界，以容纳适量的玩家。因此，即使玩家站着不动，随着其他玩家进入或离开世界，他们也可能会被分配到另一个房间。同一 `room` 中的玩家可以互相通信，并通过 MessageBus 共享消息，即使他们相距太远而无法看到彼此也是如此。同一服务器中但处于不同房间的玩家目前无法互相通信，不过他们在地图上移动并切换房间后，可能会被分配到同一房间。

若要响应玩家的 realm 或房间变化，请使用 `onChange` 函数。该函数位于 `RealmInfo` 组件上，此组件由引擎添加到 `engine.RootEntity`中。此组件包含与 `getRealm()`.

```ts
import { engine, RealmInfo } from '@dcl/sdk/ecs'

export function main() {
	RealmInfo.onChange(engine.RootEntity, (realmInfo) => {
		if (!realmInfo) return
		console.log('Realm changed: ', realmInfo.realmName)
	})
}
```

{% hint style="warning" %}
**📔 注意**：场景刚加载时，玩家可能还没有被分配房间。探索器最终会为玩家分配房间，但有时这会在场景加载几秒后才发生。
{% endhint %}

## 获取玩家的平台信息

玩家可以通过多种平台访问 Decentraland，包括官方桌面应用，以及已弃用的网页版和桌面版，还有 [其他实验性客户端](https://github.com/decentraland/protocol-squad) （基于其他引擎构建）。

使用 `getExplorerInformation()` 可了解当前玩家通过哪个平台运行 Decentraland。

```ts
import { getExplorerInformation } from '~system/Runtime';

executeTask(async () => {
  let data = await getExplorerInformation({})
  console.log("PLATFORM: ", data.platform, " AGENT: ", data.agent)
})
```

使用 Decentraland 官方桌面应用时，此函数应返回以下数据：

```
{
    agent: unity-explorer,
    platform: desktop
}
```

使用 Decentraland 官方桌面应用的玩家，很可能比使用浏览器的玩家获得更流畅的体验，因为浏览器会限制浏览器标签页可使用的机器处理能力。此外，他们还无法使用许多功能，例如摄像机控制、动态光照、冻结玩家移动、UI 增强等。

## 获取玩家语言

使用 `getPlayerLanguage()` 以了解玩家客户端设置的语言。它会返回一个 [BCP 47](https://en.wikipedia.org/wiki/IETF_language_tag) 标签，例如 `'en'`, `'es'` 或 `'pt-BR'`。使用它来选择要显示的场景文本译文。

```ts
import { getPlayerLanguage, onPlayerLanguageChanged } from '@dcl/sdk/platform'

console.log('LANGUAGE: ', getPlayerLanguage())

// 响应玩家在会话中途切换语言
onPlayerLanguageChanged.add(({ language }) => {
  console.log('LANGUAGE CHANGED TO: ', language)
})
```

`onPlayerLanguageChanged` 会在玩家处于你的场景中并更改客户端语言时触发。旧版客户端不会触发此事件。

{% hint style="warning" %}
**📔 注意**: `getPlayerLanguage()` 会返回 `'en'` 直到 explorer 将其语言报告给场景为止；这会在场景启动后不久发生。它还会返回 `'en'` 对于未报告语言的客户端。这两个函数都需要 `@dcl/sdk` 7.30.0 或更高版本。
{% endhint %}

## EngineInfo 组件

这个 `EngineInfo`组件会跟踪场景生命周期相关的数据，有时可用于判断某个事件相对于场景初始化发生的时间。

此组件会添加到 `engine.RootEntity`.

```ts
engine.addSystem((deltaTime) => {
  const engineInfo = EngineInfo.getOrNull(engine.RootEntity)
  if (!engineInfo) return

  console.log(
    '--------------' +
      '\n帧编号：' +
      engineInfo.frameNumber +
      '\n刻号：' +
      engineInfo.tickNumber +
      '\n总运行时间：' +
      engineInfo.totalRuntime +
      '\n场景已隐藏：' +
      engineInfo.sceneHidden +
      '\n--------------'
  )
})
```

你可以使用 `sceneHidden` 在场景不可见时暂停资源密集型工作：

```ts
engine.addSystem((deltaTime) => {
  const engineInfo = EngineInfo.getOrNull(engine.RootEntity)
  if (engineInfo?.sceneHidden) return

  // 仅当场景可见时才运行正常的游戏逻辑
})
```

其中， `EngineInfo` 组件包含以下数据：

* `frameNumber`：引擎的帧计数器。
* `totalRuntime`：此场景的总运行时间，以秒为单位。
* `tickNumber`：按照以下规范定义的场景 tick 计数器： [ADR-148](https://adr.decentraland.org/adr/ADR-148).
* `sceneHidden`: `true` 表示场景被 Explorer 的全屏界面遮挡。这包括加载界面、地图、背包和设置菜单。可以据此在玩家看不到场景时将音频静音并暂停资源密集型工作。

{% hint style="warning" %}
**📔 注意**： `EngineInfo` 组件必须通过以下方式导入：

> `import { EngineInfo } from "@dcl/sdk/ecs"`

有关如何轻松处理这些内容，请参阅 [导入](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 。
{% endhint %}

### 响应加载界面淡出

其中， `scene_hidden` 字段用于判断玩家是否能看到你的场景，或者场景是否被 Explorer 的全屏界面遮挡。加载界面显示时， `sceneHidden` 为 `true`。加载界面淡出、玩家首次看到世界的那一刻，它会变为 `false`.

之后，每当 Explorer 的全屏界面遮挡场景时，它都会再次变为 `true` ，例如打开地图、背包或设置菜单时。因此，可以用它作为信号，将 [音频](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/sounds.md) 静音并暂停资源消耗大的系统，然后在它恢复为 `false`.

这是场景获知首次呈现时刻的唯一方式。可以据此推迟播放或执行那些可能在加载界面背后发生、从而被玩家错过的内容：片头动画、欢迎音效、只有观看完整过程才能理解的补间动画、开场界面，或只应在玩家真正进入场景后才计数的分析事件。

```ts
import { engine, EngineInfo } from '@dcl/sdk/ecs'

function onSceneRevealed() {
  // 玩家现在可以看到场景，在此处开始播放片头
  console.log('The loading screen just faded out')
}

engine.addSystem(function waitForSceneRevealed() {
  const engineInfo = EngineInfo.getOrNull(engine.RootEntity)
  if (!engineInfo || engineInfo.sceneHidden) return

  // 仅运行一次
  engine.removeSystem(waitForSceneRevealed)
  onSceneRevealed()
})
```

{% hint style="warning" %}
**📔 注意**：你的场景会继续正常运行，即使 `sceneHidden` 为 `true`时，场景只是不会显示，并未停止运行。不要用此字段暂停场景逻辑，而应使用它来控制玩家应当看到的内容何时出现。

`scene_hidden` 需要使用最新版本的 `@dcl/sdk` 以及较新版本的 Decentraland Explorer。在较旧的客户端中，此字段会保持默认值 `false`，因此等待此字段的场景仍会运行——只是无法与加载屏幕的淡出效果同步。
{% endhint %}


---

# 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-zh/chang-jing-sdk7/jiao-hu-xing/runtime-data.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.
