Skip to content

コードからのトリガー実行 ​

本ページでは、スクリプト(C#)から OnTrigger メソッドを呼び出し、任意のタイミングや条件下で破壊を実行する実践的な実装パターンを3つ紹介します。

BaseDestructionの利用について

以下のサンプルコードでは、コンポーネントの参照に InstantDestructionSimple などの具体的なクラスではなく、その継承元である BaseDestruction を使用しています。これにより、将来的に破壊コンポーネントの種類を変更した場合でも、呼び出し側のスクリプトを修正することなくそのまま動作させることができるため、拡張性に優れています。

1. Simple Destruction (シンプルな呼び出し) ​

最も基本的なパターンです。あらかじめインスペクター等で参照しておいた対象オブジェクトに対して破壊をトリガします。

csharp
using UnityEngine;
using InstantDestruction;

public class SimpleDestroyer : MonoBehaviour
{
    [SerializeField] private BaseDestruction targetDestruction;

    public void ExecuteDestruction()
    {
        if (targetDestruction != null)
        {
            // Trigger destruction from the center of the object
            targetDestruction.OnTrigger();
        }
    }
}

2. Area Explosion (範囲爆発による破壊) ​

爆弾などを想定したパターンです。Physics.OverlapSphere を使用して特定の座標から一定範囲内にある破壊可能オブジェクトを検出し、まとめて破壊します。引数に爆発の中心座標を渡すことで、そこを起点として破片が飛び散ります。

csharp
using UnityEngine;
using InstantDestruction;

public class BombExplosion : MonoBehaviour
{
    [SerializeField] private Transform targetTransform;
    [SerializeField] private float explosionRadius = 5f;

    public void Explode()
    {
        Vector3 explosionCenter = targetTransform.position;

        // Find all colliders within the explosion radius
        Collider[] hitColliders = Physics.OverlapSphere(explosionCenter, explosionRadius);

        foreach (Collider hitCollider in hitColliders)
        {
            // Check if the object has the BaseDestruction component
            if (hitCollider.TryGetComponent<BaseDestruction>(out var destruction))
            {
                // Trigger destruction with the explosion center as the origin
                destruction.OnTrigger(explosionCenter);
            }
        }
    }
}

3. Raycast Shooting (銃撃などによる破壊) ​

銃などの射撃を想定したパターンです。レイキャスト(Physics.Raycast)を使用して着弾点を取得し、その座標を OnTrigger に渡すことで、弾が当たった箇所から破片を正確に吹き飛ばすことができます。

csharp
using UnityEngine;
using InstantDestruction;

public class RaycastShooter : MonoBehaviour
{
    [SerializeField] private Transform gunMuzzle;
    [SerializeField] private float shootRange = 100f;

    public void Shoot()
    {
        // Shoot a ray from the muzzle forward
        if (Physics.Raycast(gunMuzzle.position, gunMuzzle.forward, out RaycastHit hit, shootRange))
        {
            // Check if the hit object has the BaseDestruction component
            if (hit.collider.TryGetComponent<BaseDestruction>(out var destruction))
            {
                // Trigger destruction using the exact hit point as the explosion center
                destruction.OnTrigger(hit.point);
            }
        }
    }
}