コガネブログ

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

【Unity】【Tips】拡張メソッドを定義して文字列判定を短く記述する

Before

if ( other.collider.tag == "Enemy" || 
     other.collider.tag == "Wall"  || 
     other.collider.tag == "Bullet" 
)
{
    ...
}

After

using System.Linq;

public static class GenericExtensions
{
    public static bool ContainsAny<T>( this T self, params T[] values )
    {
        return values.Any( c => c.Equals( self ) );
    }
}
if ( other.collider.tag.ContainsAny( "Enemy", "Wall", "Bullet" )
{
    ...
}

関連記事