# 服務

有時候需要一個可以從所有角色和組件訪問的類。這可以通過服務來實現,服務是可以注入到角色和組件中的類。每個服務只會有一個實例。這類似於單例設計模式。它可以用於多種目的:

1. **Global access/全面使用權:** 服務提供了一種便捷的方式,可以從遊戲代碼的任何地方訪問特定對象或功能。這對於管理和共享資源、遊戲狀態或音頻管理器、輸入處理器、配置設置等服務很有幫助。
2. **Game state management/遊戲狀態管理:** 服務可用於管理遊戲的整體狀態,包括分數、關卡進度或當前遊戲模式等方面。這有助於在代碼的各個部分保持一致的遊戲狀態。
3. **Configuration settings/配置設置:** 存儲和訪問全局配置設置或變量是一個常見用例。
4. **Cross-actor communication/跨角色通信**: 服務可以通過提供共享接口來促進不同角色或系統之間的通信。例如,可以在服務上放置事件發射器,以在事件發生時通知遊戲中的每個角色。

## 創建服務

要創建服務,只需在類上添加 `@Service()` 裝飾器即可。

<pre class="language-typescript"><code class="lang-typescript"><strong>// src/services/game-state.ts
</strong><strong>import { Service } from "@hology/core/gameplay";
</strong>
@Service()
class GameState {
  score: number
}

export default GameState
</code></pre>

## 注入服務

可以通過使用inject函數並傳入服務的類來在任何角色或組件中使用服務。

```typescript
// src/actors/goal.ts
import { Actor, BaseActor, inject, } from "@hology/core/gameplay";
import Service from "../services/game-state.ts"

@Actor()
class Goal extends BaseActor {
  private gameState = inject(GameState)
}
```

## 內置服務

以下是一些可能對你有用的服務,同時也為服務提供了示例用例。

* **World**: 世界服務可用於生成角色。
* **PhysicsSystem**: 管理遊戲中的所有物理。可用於為角色設置物理、對角色施加力,以及訂閱碰撞事件。
* **ViewController**: 引擎渲染的接口。可用於設置活動攝像機或暫停/恢復渲染。


---

# Agent Instructions: 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:

```
GET https://docs.hology.app/zh-tw/gameplay/fu-wu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
