Alternative Source Generator is built on the Unity native functions.
- ✅ Unity Package Manager Support
- ✅ No Complicated IDE Environment Setup
- ✅ No Additional Package Installation
As you already know, Roslyn's source generator is too sophisticated. This framework provides more simple, ease of use and good enough functions for source code generation.
日本語 / JA
超簡単に使える Unity 向けソースジェネレーターです。
📃 Table of Contents
Here is minimal implementation of source generator.
See API Reference for further details.
日本語 / JA
最小限のソースジェネレーターの構成はこちら。StringBuilder
が渡されるので書き込んで true
を返せば context.OutputPath
に内容を書き込みます。false
を返せば書き込みを中止できます。
This example will add Panic()
method to target class.
日本語 / JA
ターゲットのクラスに Panic()
メソッドを追加するサンプル。
public class PanicMethodGenerator
{
static string OutputFileName() => "PanicMethod.cs"; // -> PanicMethod.<TargetClass>.<GeneratorClass>.g.cs
static bool Emit(USGContext context, StringBuilder sb)
{
if (!context.TargetClass.IsClass || context.TargetClass.IsAbstract)
return false; // return false to tell USG doesn't write file.
// code generation
sb.Append($@"
namespace {context.TargetClass.Namespace}
{{
internal partial class {context.TargetClass.Name}
{{
public void Panic() => throw new System.Exception();
}}
}}
");
return true;
}
}
using SatorImaging.UnitySourceGenerator;
namespace Sample
{
// Add attribute to target class to use method generator.
// Note that class must be defined as partial class.
[UnitySourceGenerator(typeof(PanicMethodGenerator), OverwriteIfFileExists = false)]
internal partial class MethodGeneratorSample
{
}
}
Generated code looks like this.
// <auto-generated>PanicMethodGenerator</auto-generated>
namespace Sample
{
internal partial class MethodGeneratorSample
{
public void Panic() => throw new System.Exception();
}
}
Here is target-less, self-emitting generator example.
It is useful to generate static database that cannot be generated on Unity runtime. For example, build asset GUIDs database using UnityEditor.AssetDatabase
, resource integrity tables, etc.
using System.Text;
using SatorImaging.UnitySourceGenerator;
[UnitySourceGenerator(OverwriteIfFileExists = false)]
class MinimalGenerator
{
static string OutputFileName() => "Test.cs"; // -> Test.<ClassName>.g.cs
static bool Emit(USGContext context, StringBuilder sb)
{
// write content into passed StringBuilder.
sb.AppendLine($"Asset Path: {context.AssetPath}");
sb.AppendLine($"Hello World from {typeof(MinimalGenerator)}");
// you can modify output path. initial file name is that USG updated.
// NOTE: USG doesn't care the modified path is valid or not.
context.OutputPath += "_MyFirstTest.txt";
// return true to tell USG to write content into OutputPath. false to do nothing.
return true;
}
}
// <auto-generated>MinimalGenerator</auto-generated>
Asset Path: Assets/Scripts/MinimalGenerator.cs
Hello World from Sample.MinimalGenerator
Source Generator creates USG.g
folder next to target script and append class names to file name.
Resulting file path will be:
- Assets/Scripts/USG.g/Test.MinimalGenerator.g.cs
- Assets/Scripts/USG.g/PanicMethod.MethodGeneratorSample.PanicMethodGenerator.g.cs
日本語 / JA
書き出し先は上記の通り。フォルダーとターゲット・ジェネレータークラス名が付与されます。
NOTE: In above example, output path is modified so that resulting file name is
Test.MinimalGenerator.g.cs_MyFirstTest.txt
There are utility methods for coding source generator more efficient and readable.
StringBuilder
ExtentionsIndentLine
/IndentAppend
IndentBegin
/IndentEnd
IndentLevel
/IndentChar
/IndentSize
USGFullNameOf
usg
USGReflection
* can be used on Unity runtimeGetAllPublicInstanceFieldAndProperty
TryGetFieldOrPropertyType
GetEnumNamesAndValuesAsDictionary
GetEnumNamesAndValuesAsTuple
// indent utility
sb.IndentChar(' '); // default
sb.IndentSize(4); // default
sb.IndentLevel(3); // template default
sb.IndentBegin("void MethodName() {");
{
// cast int value to enum
sb.IndentLine($"MyObject.EnumValue = ({usg<MyEnum>()})intValue");
// --- or ---
string CAST_MY_ENUM = "(" + usg(targetTypeVar) + ")";
sb.IndentLine($"MyObject.EnumValue = {CAST_MY_ENUM}intValue");
}
sb.IndentEnd("}");
usg
is a special utility that is designed for refactoring-ready source generator more readable, script template import it as a static library by default.
日本語 / JA
System.Reflection
系のユーティリティーと StringBuilder
の拡張メソッド群。
usg
は特殊で、クラス名やら何やらのリファクタリングに強いジェネレーターにすると読みづらくなってしまうのを緩和するためのモノ。
{typeof(MyClass).FullName}.{nameof(MyClass.Property)}
どんどん長くなるだけなら良いけどクラス内クラスとか構造体の名前が + 付きの不正な状態で出てくる。その他にもジェネリッククラスへの対応とかなんとか、結局何かが必要になる。それならばと可能な限り短く書けるようにした。
インデント系はトリッキーだけど開発機での実行なのでまあ良し。
using static SatorImaging.UnitySourceGenerator.USGFullNameOf; // usg<T>() to work
// usg<T>() allows to write refactoring-ready code with auto completion
sb.Append($"public static {usg<Dictionary<int, float>>()} MyDict = new() {{ init... }};");
// usg<T>{params string[]) to generate full name with specified member name.
usg<MyClass>("NestedStruct.MyField"); // -> global::Full.Namespace.To.MyClass.MyStruct.MyField
// most strict refactoring-ready code
usg<MyClass>(nameof(MyClass.NestedStruct), nameof(MyClass.NestedStruct.MyField));
// usg(object valueOrType, bool isFullName) to retrieve full type definition literal
static class MyClass {
Dictionary<int, List<Dictionary<string, float[][]>[]>> Complex = new(0); // usg() throws when null
}
usg(MyClass.Complex); // -> global::...Dictionary<int, global::...List<global::...Dictionary<string, float[][]>[]>>
This sample allows you to handle scene index more efficiently.
To use this sample, add [UnitySourceGenerator(typeof(SceneBuildIndexGenerator))]
attribute to your class. after that, you can use the following enum and helper methods.
-
enum
SceneBuildIndex
- enum consists of scene file names which registered in build settings.
- easy to use with Unity inspector. note that class field doesn't track build index changes.
-
static class
SceneBuildIndexResolver
-
GetByName(string sceneFileNameWithoutExtension)
- get build index by scene name or throws if scene is not found.
- this method ensures the scene must be included in build and also track build index changes.
// use like this in entry point to validate scene existence SceneBuildIndex ImportantSceneIndex = SceneBuildIndexResolver.GetByName("Scene_Must_Be_Included_in_Build");
-
GetListByPrefix(string fileNamePrefix)
- Get list of index which starts with prefix.
-
GetListByPath(string assetsPath)
- Path must be started with "Assets/".
-
There are utility functions to perform source code generation on build event.
日本語 / JA
IPostprocessBuildWithReport
も実装しようかと思ったものの、ビルドイベントに勝手に処理追加するのはなんか訳わからんが動かんの原因だし、BuildReport として渡される全てのファイル名を走査する処理は効率も良くない。ということで。
// generate code for specified generator type
USGUtility.ForceGenerateByType(typeof(MinimalGenerator));
// or for the emitter type
USGUtility.ForceGenerateByType(typeof(ClassHasUSGAttribute));
As of C# 9.0, it doesn't allow to define abstract static
methods in interface, USG reports error when source generator class doesn't implement required static methods.
日本語 / JA
理想はアトリビュートとインターフェイスによるフィルタリングですが、Unity 2021 は C# 9.0 で abstract static
を含んだインターフェイスが使えません。
しょうがないのでメソッドのシグネチャを確認して存在しなければエラーをコンソールに出します。
- Generator/target class name and filename must be matched.
Class name must be unique in whole project.Classes are ignored if defined in assembly which name starts with:Unity
(no trailing dot)System.
Mono.
日本語 / JA
- ジェネレーター・対象クラスの名前はファイル名と一致
ジェネレータクラスの名前はプロジェクト内で一意クラスが以下で始まる名前のアセンブリで宣言されている場合は対象としないUnity
(末尾ドット無し)System.
Mono.
USG automatically adds document tag at the beginning of generated file. You can remove this document tag by sb.Clear()
in Emit()
method.
日本語 / JA
渡される StringBuilder
の冒頭にはドキュメントタグが入ってます。不要なら sb.Clear()
してください。
Use the following git URL in Unity Package Manager (UPM).
- Latest: https://github.com/sator-imaging/Unity-AltSourceGenerator.git
- v3.0.0: https://github.com/sator-imaging/Unity-AltSourceGenerator.git#v3.0.0
- v2.0.1: https://github.com/sator-imaging/Unity-AltSourceGenerator.git#v2.0.1
-
Main Menu > Edit > Project Settings > Alternative Source Generator
-
On
- Include generator in auto run sequence.
-
Run
- Run generator on demand. Note that
OverwriteIfFileExists
setting on attribute is ignored.
- Run generator on demand. Note that
-
Link
- Click name to unveil generator script file in project window.
- Down arrow icon (▼) will show referencing emitters below.
- Linked chain icon (🔗) to unveil emitted file in
USG.g
folder.
-
🗑️
- Delete emitted file from
USG.g
folder.
- Delete emitted file from
-
-
Main Menu > Tools > Alternative Source Generator
- open as a window.
日本語 / JA
手動でソースコード生成イベントの発火も可能です。「ジェネレーターのスクリプトファイル」か「生成されたファイル」を選択して、Project ウインドウで Reimport
か Unity Source Generator
以下のメニューを実行します。
ジェネレーターとして参照されているファイルを Reimport した場合は、関連するクラスすべてが再生成されます。Force Generate...
はクラスアトリビュートの設定に関わらず強制的に上書き生成します。
There is an ability to invoke source code generation by hand. With generator script file or generated file selected in Project window:
-
Reimport
- This command respects
OverwriteIfFileExists
setting by generator class attribute. - Classes referencing selected generator will also be re-generated.
- This command respects
-
Unity Source Generator > Force Generate
- This command will force re-generate source code even if overwrite setting is disabled.
Usually, this problem happens when Unity automatically reloads updated scripts WITHOUT Editor window getting focus. To solve the problem:
- Close Unity and Visual Studio.
- Restart Unity.
- Launch Visual Studio by double clicking
.cs
script in Unity Editor.
NOTE: There is experimental feature to suspend auto reloading while Unity Editor in background (doesn't get focused). Open
Edit > Project Settings > Alternative Source Generator
to enable it.
Copyright © 2023-2024 Sator Imaging, all rights reserved.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
MIT License
Copyright (c) 2023-2024 Sator Imaging
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
GenerateOnce
attribute parameter- currently USG generates same class/enum multiple times when multiple classes refer enum/singleton generator.
- ex.
SceneBuildIndex
must be referred only once in project to avoid conflict
- v4: remove obsolete functions
- support C# 11 language features (waiting for Unity 6 update!!)
- see also: CHANGELOG