> 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()` 该函数是异步的。请参阅 [异步函数](/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/async-functions.md) 如果你不熟悉这些内容。
{% endhint %}

`getWorldTime()` 返回一个带有一个 `seconds` 属性。该属性表示自一天开始以来已经过去了多少秒（以 Decentraland 时间计），假设完整循环持续 24 小时。将 seconds 值除以 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('正在播放蟋蟀声')
  } else {
    // 白天
    console.log('正在播放鸟叫声')
  }
})
```

## 获取 realm 数据

Decentraland 中的玩家存在于几个彼此独立的 *领域*。不同 Realm 中的玩家彼此无法看见、互动或聊天，即使他们站在同一地块上也是如此。这样划分玩家可以让 Decentraland 处理无限数量的玩家，而不会遇到任何限制。它还会将彼此靠近区域的玩家配对，以确保互动玩家之间的 ping 延迟处于可接受范围内。

如果你的场景向一个 [第三方服务器](/creator/content-creator-zh/chang-jing-sdk7/wang-luo/third-party-servers.md) 用于在玩家之间实时同步更改，那么通常很重要的是，更改只应在同一 Realm 的玩家之间同步。你应该将属于一个 Realm 的所有更改与另一个 Realm 的更改分开处理。否则，玩家会看到事物以一种诡异的方式变化，却没有任何人做出更改。

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

executeTask(async () => {
  const { realmInfo } = await getRealm({})
  if (!realmInfo) return
  console.log(`You are in the realm: `, realmInfo.realmName)
})
```

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

Decentraland 通过一个去中心化的通信服务器网络来处理玩家之间的通信（包括玩家位置、聊天、messageBus 消息和 smart item 状态变化），其中每个服务器都称为一个 **Realm**。这些服务器中的每一个都可以支持多个独立的 **房间** （也称为 **岛屿**），每个房间会将 Decentraland 地图上彼此相近的一组不同玩家归为一组。

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

* `baseUrl`: *(string)* Realm 服务器的域名
* `realmName`: *(string)* Realm 服务器的名称
* `networkId`: *(number)* 以太坊网络
* `commsAdapter`: *(string)* 通信适配器，已移除所有查询参数（凭据）
* `isPreview`: *(boolean)* 如果场景作为本地预览运行，而不是发布在 Decentraland 中，则为真。
* `isConnectedSceneRoom`: *(boolean)* 如果用户已连接到场景房间，则为真。

{% 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 已更改：', realmInfo.realmName)
	})
}
```

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

## 获取玩家平台

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

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

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

executeTask(async () => {
  let data = await getExplorerInformation({})
  console.log("平台：", data.platform, " 代理：", data.agent)
})
```

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

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

使用官方 Decentraland 桌面应用的玩家，体验很可能比浏览器端流畅得多，因为浏览器会对浏览器标签页可使用的机器处理能力施加性能限制。他们也会缺少许多功能，例如摄像机控制、动态光照、冻结玩家移动、UI 增强等。

## EngineInfo 组件

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

该组件会被添加到 `engine.RootEntity`.

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

  console.log(
    '--------------' +
      '\nframeNumber: ' +
      engineInfo.frameNumber +
      '\ntickNumber: ' +
      engineInfo.tickNumber +
      '\ntotalRuntime: ' +
      engineInfo.totalRuntime +
      '\nsceneHidden: ' +
      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`: `真` 当场景被 Explorer 的全屏 UI 遮住时。包括加载界面，以及地图、背包和设置菜单。可在玩家看不到场景时用它来静音音频并暂停耗时较高的工作。

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

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

参见 [导入](/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 了解如何轻松处理这些。
{% endhint %}

### 响应加载界面的淡出

该 `scene_hidden` 字段会告诉你玩家是否真正能看到你的场景，或者它是否被 Explorer 的全屏 UI 覆盖。加载界面显示时， `sceneHidden` 为 `真`。当加载界面淡出、玩家第一次看到世界时，它会变为 `false`.

会变为 `真` ，之后当任何全屏 Explorer UI 覆盖场景时也会再次变为，例如地图、背包或设置菜单。这使它成为静音的一个好信号 [音频](/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/sounds.md) 并暂停耗费资源的系统，然后在它返回为 `false`.

这是场景得知首次完全显现发生时的唯一方式。可用它来阻止任何原本会在加载界面后面播放、而玩家会错过的内容：开场过场动画、欢迎音效、只有在被观看时才有意义的补间动画、开场 UI，或者应只在玩家真正到场后才计数一次的分析事件。

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

function onSceneRevealed() {
  // 玩家现在正在看这个场景，在这里开始开场内容
  console.log('加载界面刚刚淡出')
}

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

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

{% hint style="warning" %}
**📔 注意**：当 `sceneHidden` 为 `真`时，你的场景仍会正常运行，只是没有被显示出来。不要使用这个字段来暂停场景逻辑，而应使用它来把握玩家本该看到的内容的时机。

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