You can use source generators as an additional step in your script compilation process, to add new code while you compile your existing code. As with code analyzers, you can use existing source generators or create your own.
Note: Unity only supports version 6.0.0-preview of the System.Text.Json
namespace. If you want to use this namespace in your application, ensure you use version 6.0.0-preview
. For more information about System.Text.Json
, refer to Microsoft’s System.Text.Json Namespace documentation.
To create a source generator in Visual Studio and then apply it for use in your Unity project:
In Visual Studio, create a C# class library project that targets .NET Standard 2.0 and name the project ExampleSourceGenerator
.
Install the Microsoft.CodeAnalysis.Csharp
NuGet package for the project. Your source generator must use Microsoft.CodeAnalysis.Csharp 4.3 to work with Unity.
In your Visual Studio project, create a new C# file and add the following code:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
namespace ExampleSourceGenerator
{
[Generator]
public class ExampleSourceGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
System.Console.WriteLine(System.DateTime.Now.ToString());
var sourceBuilder = new StringBuilder(
@"
using System;
namespace ExampleSourceGenerated
{
public static class ExampleSourceGenerated
{
public static string GetTestText()
{
return ""This is from source generator ");
sourceBuilder.Append(System.DateTime.Now.ToString());
sourceBuilder.Append(
@""";
}
}
}
");
context.AddSource("exampleSourceGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}
public void Initialize(GeneratorInitializationContext context) { }
}
}
Build your source generator for release. To do this, go to Build and select the Batch Build option, then select the Release option and Build.
In your source generator’s project folder, find the bin/Release/netstandard2.0/ExampleSourceGenerator.dll
file.
Copy this file into your Unity project, inside the Assets folder.
Inside the Asset Browser, click on the .dll file to open the Plugin Inspector window.
Under Select platforms for plugin, disable Any Platform.
Under Include Platforms, disable Editor and Standalone.
Under Asset Labels, click on the label icon to open the Asset labels sub-menu.
Create and assign a new label called RoslynAnalyzer. To do this, type RoslynAnalyzer
in the text input fieldA field that allows the user to input a Text string More info
See in Glossary of the Asset labels sub-menu and press enter. This label must match exactly and is case sensitive. Once created, the label appears in the Asset labels sub-menu from then on. You can click on the name of the label in the menu to assign it to other analyzers.
A warning will be printed in the console because this source generator will get injected into more than one assembly. The solution is to make ExampleSourceGenerated
in the above example internal or the name itself should be generated.
To test the source generator is working, create a new MonoBehaviour script in the Editor with the following code:
using UnityEngine;
public class HelloFromSourceGenerator : MonoBehaviour
{
static string GetStringFromSourceGenerator()
{
return ExampleSourceGenerated.ExampleSourceGenerated.GetTestText();
}
// Start is called before the first frame update
void Start()
{
var output = "Test";
output = GetStringFromSourceGenerator();
Debug.Log(output);
}
}
Add this script to a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary in the sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary and enter Play mode. A message from the source generator will appear in the Console windowA Unity Editor window that shows errors, warnings and other messages generated by Unity, or your own scripts. More info
See in Glossary, including the time stamp. A warning will also appear in the console because this source generator will get injected into more than one assembly. The solution is to make ExampleSourceGenerated
in the above example internal or the name itself should be generated.
For more information about source generators, refer to Microsoft’s Source Generators documentation.
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.