コガネブログ

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

【Unity】LINQ で抽出した要素をログ出力して確認できるようにする拡張メソッド

ソースコード

using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

namespace Kogane
{
    public static class IEnumerableLogExtensionMethods
    {
        public delegate void LogDelegate( object item );

        public static LogDelegate OnLog        { get; set; } = item => Debug.Log( item );
        public static LogDelegate OnLogWarning { get; set; } = item => Debug.LogWarning( item );
        public static LogDelegate OnLogError   { get; set; } = item => Debug.LogError( item );

        public static IEnumerable<T> Log<T>( [NotNull] this IEnumerable<T> source )
        {
            if ( source == null ) throw new ArgumentNullException( nameof( source ) );

            IEnumerable<T> Iterator()
            {
                foreach ( var x in source )
                {
                    OnLog?.Invoke( x );
                    yield return x;
                }
            }

            return Iterator();
        }

        public static IEnumerable<T> LogWarning<T>( [NotNull] this IEnumerable<T> source )
        {
            if ( source == null ) throw new ArgumentNullException( nameof( source ) );

            IEnumerable<T> Iterator()
            {
                foreach ( var x in source )
                {
                    OnLogWarning?.Invoke( x );
                    yield return x;
                }
            }

            return Iterator();
        }

        public static IEnumerable<T> LogError<T>( [NotNull] this IEnumerable<T> source )
        {
            if ( source == null ) throw new ArgumentNullException( nameof( source ) );

            IEnumerable<T> Iterator()
            {
                foreach ( var x in source )
                {
                    OnLogError.Invoke( x );
                    yield return x;
                }
            }

            return Iterator();
        }
    }
}

使用例

using System.Linq;
using Kogane;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
#if ENABLE_RELEASE
        IEnumerableLogExtensionMethods.OnLog        = null;
        IEnumerableLogExtensionMethods.OnLogWarning = null;
        IEnumerableLogExtensionMethods.OnLogError   = null;
#else
        IEnumerableLogExtensionMethods.OnLog        = x => Debug.Log( x );
        IEnumerableLogExtensionMethods.OnLogWarning = x => Debug.LogWarning( x );
        IEnumerableLogExtensionMethods.OnLogError   = x => Debug.LogError( x );
#endif

        var list1 = Enumerable.Range( 0, 3 ).Log().ToArray();
        var list2 = Enumerable.Range( 0, 3 ).LogWarning().ToArray();
        var list3 = Enumerable.Range( 0, 3 ).LogError().ToArray();
    }
}