1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Unity】カラーのスワッチライブラリから定数定義用のCSファイルを生成する

Posted at

の続きです。

概要

スワッチライブラリに使用されている ColorPresetLibrary クラスが private なためリフレクションでカラーと名前を取得し、cs ファイルに出力する Editor 拡張です。

コード全文

using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public static class ColorFileCreater
{
    private static readonly string ClassFormat =
@"using UnityEngine;

public static class {0}
{{{1}
}}";

    private static readonly string VariableFormat = "\tpublic static readonly Color {0} = new Color({1}f, {2}f, {3}f, {4}f);";

    [MenuItem( "Assets/Color File Create" )]
    private static void Create()
    {
        var libraryName = "TextColor";
        var library = AssetDatabase.LoadAssetAtPath( $"Assets/Editor/{libraryName}.colors", typeof( Object ) );
        var type = library.GetType();
        var contents = new StringBuilder();
        for( var i = 0; i < (int)type.GetMethod( "Count" ).Invoke( library, null ); i++ )
        {
            contents.AppendLine();
            var param = new object[] { i };
            var color = (Color)type.GetMethod( "GetPreset" ).Invoke( library, parameters: param );
            var name = type.GetMethod( "GetName" ).Invoke( library, parameters: param );
            contents.Append( string.Format( VariableFormat, name, color.r, color.g, color.b, color.a ) );
        }

        var output = string.Format( ClassFormat, $"{libraryName}", contents );
        File.WriteAllText( $"{Application.dataPath}/{libraryName}.cs", output );
        AssetDatabase.Refresh();
    }
}

対象にしたスワッチライブラリ
ファイル名

出力されるファイル

using UnityEngine;
public static class TextColor
{
	public static readonly Color Red = new Color(1f, 0f, 0.1414824f, 1f);
	public static readonly Color Blue = new Color(0f, 0.4326849f, 1f, 1f);
	public static readonly Color Green = new Color(0.1320784f, 1f, 0f, 1f);
	public static readonly Color White = new Color(0.8679245f, 0.8679245f, 0.8679245f, 1f);
	public static readonly Color Black = new Color(0f, 0f, 0f, 1f);
}

注意点

・カラーの Name 設定が必須

スクリプトリファレンス

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?