ゴイサギ日記

東京でエンジニアとして頑張って何とか生きてます。。ゆる~く更新していきます

【Unity】Triggers モジュールについて

明けましておめでとうございます。もう2月ですが・・ ^_^;

今回は Particle System の Triggers モジュールについて調べてみました。
確認バージョンは 2019.1.0b2 です。

実装

Trigger モジュールは Colliders に設定したコライダーに対してパーティクルが接触した際の処理を設定することができます。

設定できる処理は以下になります。

項目 処理内容
Ignore 何もしない
Kill ParticleSystemが設定されているGameObjectを削除
Callback スクリプトに通知

今回はこの中の Callback についてまとめてみました。

コールバックを設定するスクリプトを用意します。今回は ParticleTriggerTest.cs という名前で作成して Particle System と同じ GameObject にアタッチします。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParticleTriggerTest : MonoBehaviour
{
    ParticleSystem m_particleSystem;
    List<ParticleSystem.Particle> m_enterList = new List<ParticleSystem.Particle>();
    List<ParticleSystem.Particle> m_exitList = new List<ParticleSystem.Particle>();

    void Start()
    {
        m_particleSystem = this.GetComponent<ParticleSystem>();
    }

    /// <summary>
    /// .
    /// </summary>
    void OnParticleTrigger()
    {
        // 条件に一致するパーティクルを ParticleSystem から取得する.
        int numEnter = m_particleSystem.GetTriggerParticles( ParticleSystemTriggerEventType.Enter, m_enterList );
        int numExit = m_particleSystem.GetTriggerParticles( ParticleSystemTriggerEventType.Exit, m_exitList );

        // 取得したパーティクルの色を変更する.
        for( int idx=0 ; idx < numEnter ; idx++ ){
            ParticleSystem.Particle p = m_enterList[ idx ];
            p.startColor = Color.red;   // 赤色.
            m_enterList[ idx ] = p;
        }
        for( int idx=0 ; idx < numExit ; idx++ ){
            ParticleSystem.Particle p = m_exitList[ idx ];
            p.startColor = Color.yellow; // 黄色.
            m_exitList[ idx ] = p;
        }

        // 変更したパーティクルを ParticleSystem に再設定.
        m_particleSystem.SetTriggerParticles( ParticleSystemTriggerEventType.Enter, m_enterList );
        m_particleSystem.SetTriggerParticles( ParticleSystemTriggerEventType.Exit, m_exitList );
    }
}
  1. Triggersモジュールを使用すると OnParticleTrigger が呼び出されます。
  2. インスペクタで Callback に設定した条件(Outside, Inside, Exit, Enter)ごとのパーティクルを取得するには GetTriggerParticles を使います。
  3. 取得したパーティクルのパラメータに変更を加えたら SetTriggerParticles で変更内容を適用してあげます。

上記のサンプルスクリプトはパーティクルのカラーを Enter時に赤色、Exit時に黄色 に変えています。

気になる点

OnParticleTrigger が毎フレーム呼ばれる
Outside のパーティクルを取得するために毎フレーム呼び出しになっているようです。しかも Triggers モジュールのチェックが有効になるだけで呼ばれてしまうところにも注意が必要です。

GetTriggerParticles / SetTriggersParticles の負荷が高い
こちらは ParticleSystem.GetParticles/SetParticles と同様にパーティクルの情報に直接アクセスする事が出来ず、一度配列にコピーした後に変更を加えて、再度データを流し込む必要があるため負荷が高くなります。

Colliderの登録が面倒
インスペクタ上から Colliders にコライダーを登録する必要があるのですが、数が多いと大変です。ParticleSystem.trigger.SetCollider() を使えばコライダーを登録する事ができるので スクリプトから制御するのも手ですね。

まとめ

パフォーマンスの面で気になるところが多い印象でした。こちらのフォーラムにあるように今後の更新で JobSystem によるパフォーマンス改善が出来ないかUnityさんの方で色々と試しているようですね。表現の幅は広がりそうなのでとても楽しみです。^_^

参考

Triggers モジュール - Unity マニュアル