コンテンツにスキップ

Component

継承の代わりに機能を小さな単位へ分割し、その組み合わせでエンティティを構成するパターンです。

  • キャラクター機能を柔軟に組み合わせたいとき
  • ランタイムで機能の ON/OFF を切り替える設計が必要なとき
  • Entity: コンポーネントコンテナ
  • Component: 独立した機能単位
  • Composer: 初期組み合わせ設定

以下のコードは、上で説明した状況を Unity プロジェクトの文脈で単純化した例です。

using System.Collections.Generic;
using UnityEngine;
public interface IGameComponent
{
void Tick(float deltaTime);
}
public sealed class MovementComponent : IGameComponent
{
private readonly Transform targetTransform;
private readonly float moveSpeed;
public MovementComponent(Transform targetTransform, float moveSpeed)
{
this.targetTransform = targetTransform;
this.moveSpeed = moveSpeed;
}
public void Tick(float deltaTime)
{
targetTransform.position += Vector3.forward * moveSpeed * deltaTime;
}
}
public sealed class CharacterControllerRoot : MonoBehaviour
{
private readonly List<IGameComponent> components = new();
private void Awake()
{
components.Add(new MovementComponent(transform, 5f));
}
}
  • 機能をモジュールとして分けることで、キャラクターやオブジェクトのバリエーションを素早く作れます。
  • 特定コンポーネントだけをテスト・差し替えしやすく、回帰範囲を小さくできます。
  • コンポーネント間の依存が大きくなると、別の形の結合が生まれます。
  • Update ループが各コンポーネントに分散すると、呼び出しコストとデバッグ難度が上がります。

エンティティが複数のコンポーネントを組み合わせて最終状態を作る流れです。

Component の流れ