コガネブログ

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

【Unity】string型をColor型に変換する関数を管理するクラス

Unity 5.3 から追加された「UnityEngine.ColorUtility」を使用して
string型をColor型に変換する関数を管理するクラスを作成しました

using UnityEngine;

public static class MyColorUtility
{
    /// <summary>
    /// 指定された文字列を Color 型に変換できる場合 true を返します
    /// </summary>
    public static bool IsColor( string htmlString )
    {
        Color color;
        return ColorUtility.TryParseHtmlString( htmlString, out color );
    }
    
    /// <summary>
    /// 指定された文字列を Color 型に変換します
    /// </summary>
    public static Color ToColor( string htmlString )
    {
        Color color;
        ColorUtility.TryParseHtmlString( htmlString, out color );
        return color;
    }
    
    /// <summary>
    /// <para>指定された文字列を Color 型に変換します</para>
    /// <para>変換できなかった場合デフォルト値を返します</para>
    /// </summary>
    public static Color ToColorOrDefault( string htmlString, Color defaultValue = default( Color ) )
    {
        Color color;
        if ( ColorUtility.TryParseHtmlString( htmlString, out color ) )
        {
            return color;
        }
        return defaultValue;
    }
    
    /// <summary>
    /// <para>指定された文字列を Color 型に変換します</para>
    /// <para>変換できなかった場合 null を返します</para>
    /// </summary>
    public static Color? ToColorOrNull( string htmlString )
    {
        Color color;
        if ( ColorUtility.TryParseHtmlString( htmlString, out color ) )
        {
            return color;
        }
        return null;
    }
}
Debug.Log( MyColorUtility.IsColor( "#FF0000" ) );
Debug.Log( MyColorUtility.IsColor( "red" ) );
Debug.Log( MyColorUtility.ToColor( "#FF0000" ) );
Debug.Log( MyColorUtility.ToColor( "red" ) );
Debug.Log( MyColorUtility.ToColorOrDefault( "hoge" ) );
Debug.Log( MyColorUtility.ToColorOrNull( "hoge" ) );