しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

Unity で Roslyn を使って属性クラスをコード生成する

※ これは 2023/09/21 時点の Unity 2023.1.14f1 の情報です

最新版では動作が異なる可能性がありますのでご注意ください

前回で Unity の Roslyn を使ったコード生成はできたので、今度は属性クラスをコード生成してみる

生成コード側の SourceGenerator.cs を下記のように変更

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;

namespace SourceGenerator
{
    [Generator]
    public class CodeGenerator : ISourceGenerator
    {
        /// <inheritdoc/>
        public void Initialize(GeneratorInitializationContext context)
        {
        }

        private const string Code = @"using System;

namespace Sample
{
    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
    public class SimplePropertyAttribute: Attribute
    {
        /// <summary>
        /// プロパティ名称
        /// </summary>
        public string PublicName { get; }

        /// <summary>
        /// フィールド名称
        /// </summary>
        public string LocalName { get; }

        /// <summary>
        /// コメント
        /// </summary>
        public string Comment { get; }

        /// <summary>
        /// プロパティ自動生成用属性
        /// </summary>
        /// <param name=""name"">名称</param>
        /// <param name=""comment"">コメント</param>
        public SimplePropertyAttribute(string name, string comment = null)
        {
            this.PublicName = char.ToUpper(name[0]) + name.Substring(1);
            this.LocalName = char.ToLower(name[0]) + name.Substring(1);
            this.Comment = comment;
        }
    }
}";

        /// <inheritdoc/>
        public void Execute(GeneratorExecutionContext context)
        {
            if (context.Compilation.AssemblyName.Equals("Assembly-CSharp"))
            {
                context.AddSource("SimplePropertyAttribute.g.cs", SourceText.From(Code, Encoding.UTF8));
            }
        }
    }
}

単に生成コードを属性クラスのものにしただけ

次に VSCode のソリューションエクスプローラーの右クリックメニューから「リビルド」実行

出力先プロジェクトを開いている UnityEditor に戻り、[Ctrl] + [R] で再コンパイル

試しに生成した属性をクラスに付与してみた

エラーにならずにちゃんと生成できているっぽい