Unity 中使用 Roslyn设计框架和代码规范
参考:
Get started with syntax analysis (Roslyn APIs) | Microsoft Learn
How to fix RS2008 warning? :https://github.com/dotnet/roslyn-analyzers/issues/5663
AnalysisContext Class (Microsoft.CodeAnalysis.Diagnostics) | Microsoft Learn
https://johnkoerner.com/csharp/navigating-trivia-in-your-diagnostic/
https://johnkoerner.com/csharp/navigating-trivia-in-your-diagnostic/
使用了ECS后,发现Roslyn真是个好工具。对于框架的约束的设计,终于有简单的办法不用人工Review了。
- 一、使用VS开发Analyser框架约束
- 二、开发代码规范
- 三、Roslyn的调试
- 四、在Unity中使用Analyser
一、使用VS 2022开发Analyser框架约束
1、VS中新建类库项目
2、添加NUGET包
![](http://xcodep.oss-cn-beijing.aliyuncs.com/2023/08/20230808095811117.png?x-oss-process=image/auto-orient,1/quality,q_90/format,webp)
安装 Microsoft.CodeAnalysis.CSharp.Workspaces 3.8
3.8 版本号很重要
二、开发代码规范
三、Roslyn的调试
- Add a .NET Standard 2.0 class library for your SourceGenerator.
- Set the SourceGenerator projet as Startup project.
- Edit the SourceGenerator project and replace all with:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
<IsRoslynComponent>true</IsRoslynComponent>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>
</Project>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath> <IsRoslynComponent>true</IsRoslynComponent>
上面是关键的三个配置
- Save it.
- Add a Console Application project with some examples of code you would like to test the SourceGenerator with.
- Edit the Console Application porject and add a reference to the SourceGenerator this way:
<ItemGroup> <ProjectReference Include="..\MySourceGenerator\MySourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"/> </ItemGroup>
- Save it.
- Right click on the SourceGenerator project
- Click
Properties
. - Click
Debug
. - Click
Open debug launch profiles UI
. - Click on
Delete
to delete the profile shown. - Click on
Add
- Select
Roslyn component
. - In
Target project
select the Console Application project. - Close the UI.
- Restart Visual Studio 2022.
- In the debug profiles dropdown next to the
Play
button, select your SourceGenerator project. - Put a break point in your SourceGenerator to make sure the debugger stops.
- Click
Play
.
That’s All。
四、Unity使用Analyser
Refer to : https://docs.unity.cn/cn/2022.1/Manual/roslyn-analyzers.html
Of cousrse, there are some Pits you may encounter. Don’t wary, it’s an usual.