コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Collider2D が自分自身の Bounds 内に完全に収まっている時に当たり判定のイベントを実行するクラス

ソースコード

using System;
using Kogane;
using UnityEngine;

public sealed class Example : MonoBehaviour
{
    [SerializeField] private Collider2D m_collider2D;

    private bool m_isHit;

    public event Action<Collider2D> OnEnter;
    public event Action<Collider2D> OnExit;

    private void OnTriggerStay2D( Collider2D other )
    {
        var isContains = m_collider2D.bounds.Contains( other.bounds );

        SetState( isContains, other );
    }

    private void OnTriggerExit2D( Collider2D other )
    {
        SetState( false, other );
    }

    private void SetState( bool isHit, Collider2D other )
    {
        if ( m_isHit == isHit ) return;

        var callback = isHit ? OnEnter : OnExit;
        callback?.Invoke( other );

        m_isHit = isHit;
    }
}

public static class BoundsExtensionMethods
{
    public static bool Contains( this Bounds self, Bounds other )
    {
        return self.Contains( other.min ) && self.Contains( other.max );
    }
}

使用例

using UnityEngine;

public sealed class SampleScene : MonoBehaviour
{
    [SerializeField] private Example m_example;

    private void Awake()
    {
        m_example.OnEnter += _ => Debug.Log( "OnEnter" );
        m_example.OnExit  += _ => Debug.Log( "OnExit" );
    }
}