Unityにおける依存性逆転の原則(DIP)とタグ検出の実践例

目的

Unityで、他のオブジェクトに接触したときにそのオブジェクトのメソッドを呼び出す処理を設計する際に、

  • 依存性逆転の原則(DIP)を適用するかどうか
  • タグを使って接触対象を限定するかどうか

これらの違いによる影響と、現実的な推奨設計を示します。


1. 悪い例:DIP未適用、タグ未使用

PlayerがTreasureBoxという具象クラスに直接依存している。

Player.cs

private void OnTriggerEnter(Collider other)
{
    TreasureBox box = other.GetComponent<TreasureBox>();
    if (box != null)
    {
        box.Open();
    }
}

TreasureBox.cs

public class TreasureBox : MonoBehaviour
{
    public void Open()
    {
        Debug.Log("宝箱が開いた!");
    }
}

問題点

  • TreasureBoxという具象クラスに依存しており、他の対象に拡張するにはPlayerの修正が必要
  • DIP(抽象に依存する設計)を守っていない

2. 中間例:DIP未適用、タグ使用

タグによる判定はあるが、具象クラスへの依存はそのまま。

Player.cs

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("TreasureBox"))
    {
        TreasureBox box = other.GetComponent<TreasureBox>();
        if (box != null)
        {
            box.Open();
        }
    }
}

問題点

  • タグにより判定対象を絞ってはいるが、クラス構造には柔軟性がない
  • 拡張性や保守性には乏しい

3. 安全志向:DIP適用、タグ未使用

PlayerはIInteractableという抽象インターフェースのみに依存している。

IInteractable.cs

public interface IInteractable
{
    void Interact();
}

TreasureBox.cs

public class TreasureBox : MonoBehaviour, IInteractable
{
    public void Interact()
    {
        Debug.Log("宝箱が開いた!");
    }
}

Player.cs

private void OnTriggerEnter(Collider other)
{
    IInteractable target = other.GetComponent<IInteractable>();
    if (target != null)
    {
        target.Interact();
    }
}

利点

  • Playerは抽象にしか依存しておらず、どんなIInteractable実装でも対応可能
  • 再利用性、保守性に優れる

注意点

  • すべてのIInteractableに反応してしまうため、意図しない挙動を防ぐには追加ロジックが必要

4. 推奨構成:DIP適用、タグ使用

タグで対象を絞り、処理は抽象インターフェースに委ねる構成。現実の開発において安全かつ柔軟な設計。

Player.cs

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Interactable"))
    {
        IInteractable target = other.GetComponent<IInteractable>();
        if (target != null)
        {
            target.Interact();
        }
    }
}

設定例

  • TreasureBox, Doorなどのオブジェクトに “Interactable” タグを設定
  • Playerにはトリガー付きのColliderとRigidbodyを追加

比較表

パターン再利用性拡張性保守性安全性実用性
タグなし・DIPなし低い低い低い低い不推奨
タグあり・DIPなしやや高い低い低い中程度限定的に可
タグなし・DIPあり高い高い高い中程度小規模で有効
タグあり・DIPあり高い高い高い高い推奨構成

結論

  • タグは接触対象の予備フィルターとして有効だが、処理はインターフェースなどの抽象に依存すべき
  • 依存性逆転の原則(DIP)を守ることで、拡張やテストに強い柔軟なコード設計が実現できる
  • 実務においては「タグで対象を限定しつつ、抽象に処理を委ねる構成」が最も安全で現実的

訪問数 17 回, 今日の訪問数 1回