# Actor 元件

在 Hology 中，Actor 元件扮演著至關重要的角色，它們使您能夠以清晰且有條理的方式模組化並擴展遊戲物件（actors）的功能。通過將複雜的 actors 分解為更小、可重用且易於管理的部分，Actor 元件讓您的遊戲開發過程更加高效且易於維護。

1. **模組化與可重用性：**
   * Actor 元件是獨立的功能單元，可以附加到一個或多個 actors 上。這種模組化允許您創建可重用的功能片段，這些片段可以在多個 actors 或項目中使用。
2. **組織性**:
   * Actor 元件幫助您通過將 actor 的不同行為方面分離到獨立的元件中來組織其功能。例如，您可以為角色移動、生命值、物品欄等分別創建不同的元件。
3. **代碼封裝**:
   * 每個 Actor 元件都可以封裝自己的邏輯和數據，使得管理和維護代碼更加容易。這種關注點分離有助於防止代碼重複，並保持代碼庫整潔。
4. **自定義與可擴展性:**
   * 您可以輕鬆地向 actor 添加或移除元件，以自定義其行為，而無需修改核心 actor 類。這使得迭代遊戲設計和機制變得更加簡單。
5. **編輯器友好性：**
   * Hology 的編輯器提供了一個用戶友好的介面來配置 Actor 元件，使設計師和美術人員即使沒有程式設計知識也能輕鬆使用。

## 範例元件

在以下範例中，我們有一個用於保存物件生命值狀態的元件。`max health` 是一個參數，可以在編輯器中調整，但也被賦予了一個預設值。

current health 在初始化時被設置為 max health 的值。這是因為 max health的值是在類被實例化之後才設置的，因此在定義 `currentHealth` 屬性時無法使用該值。

```typescript
@Component()
class HealthComponent extends ActorComponent {
    @Parameter() maxHealth: number = 100
    currentHealth: number
    
    onInit() {
        this.currentHealth = this.maxHealth
    }
    
    update(change: number) {
        this.currentHealth = Math.max(0, this.currentHealth + change)
    }
}
```

## 附加元件

Actors 可以通過使用 `attach(Type<ActorComponent>)` 函數將元件作為屬性添加到自身，該函數需要傳入您希望附加的類型。

```typescript
@Actor()
class CharacterActor extends BaseActor {
    health = attach(HealthComponent)
    
    takeHit(damage: number) {
        this.health.update(-damage)
    }
}
```

## 元件選項

使用 `@Component()` 裝飾器，您可以傳遞額外的選項。

```typescript
@Component({ inEditor: false, editorOnly: false })
class HealthComponent extends ActorComponent {

}
```

* **inEditor （類型：boolean，預設值：false）** - 指定該元件是否應在編輯器中使用。在編輯器中，此選項僅用於提供視覺反饋來顯示 actor 的外觀。其他功能應該被禁用。請注意，一些在遊戲中工作的功能可能無法在編輯器中運行。
* **editorOnly （類型：boolean，預設值：false）** - 指定該元件是否僅應在編輯器中使用。如果設置為 true，那麼該元件不會出現在遊戲中。這對於顯示 3D 網格非常有用，因為它可以在編輯器中提供一些視覺表示。


---

# 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/yan-yuan-actors/actor-yuan-jian.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.
