问题描述
Unity版本:2022.3.62f3c1 LTS
在项目中 Assets/ 创建csc.rsp 文件即可使用C# 10.0 ;但是 Unity 自动生成Assembly-CSharp-Editor.csproj、Assembly-CSharp-Editor.csproj文件默认使用的 C# 9.0 就会导致IDE报错;看着心烦
原因:虽然csc.rsp 文件可以让Unity执行编译时使用C#10.0语法;但是Unity 在生成项目文件的时候默认的是C# 9.0;
解决方案
1.写一个脚本,一定时间间隔遍历Unity每次生成的Assembly-CSharp-Editor.csproj、Assembly-CSharp-Editor.csproj文件;将 <LangVersion>9.0</LangVersion> 改为 <LangVersion>10.0</LangVersion>;此文件存在在Assets/Editor/ 文件目录下
2.为IDE设置语言版本;创建一个.omnisharp文件夹,与Assets同级,编写omnisharp.json配置文件
代码部分
CsProjectPostprocessor.cs 用于一定时间间隔修改文件字符
using UnityEditor; using System.IO; using UnityEngine; public class CsProjectPostprocessor : AssetPostprocessor { public static void OnGeneratedCSProjectFiles() { FixAllCsprojFiles(); } private static void FixAllCsprojFiles() { string currentDir = Directory.GetCurrentDirectory(); string[] csprojFiles = Directory.GetFiles(currentDir, "*.csproj"); foreach (string csprojFile in csprojFiles) { string content = File.ReadAllText(csprojFile); if (content.Contains("<LangVersion>9.0</LangVersion>")) { content = content.Replace("<LangVersion>9.0</LangVersion>", "<LangVersion>10.0</LangVersion>"); File.WriteAllText(csprojFile, content); Debug.Log($"[CsProjectPostprocessor] Updated LangVersion to 10.0 in: {Path.GetFileName(csprojFile)}"); } } // 刷新 Assets 文件夹,确保 Unity 识别修改 AssetDatabase.Refresh(); } } [InitializeOnLoad] public class CsprojVersionMonitor { private static double _lastCheckTime; private const double CHECK_INTERVAL = 1.0f; static CsprojVersionMonitor() { EditorApplication.update += OnEditorUpdate; _lastCheckTime = EditorApplication.timeSinceStartup; } private static void OnEditorUpdate() { if (EditorApplication.timeSinceStartup - _lastCheckTime >= CHECK_INTERVAL) { _lastCheckTime = EditorApplication.timeSinceStartup; FixCsprojFilesIfNeeded(); } } private static void FixCsprojFilesIfNeeded() { if (EditorApplication.isPlayingOrWillChangePlaymode) { return; } string currentDir = Directory.GetCurrentDirectory(); string[] csprojFiles = Directory.GetFiles(currentDir, "*.csproj"); bool filesModified = false; foreach (string csprojFile in csprojFiles) { try { string content = File.ReadAllText(csprojFile); if (content.Contains("<LangVersion>9.0</LangVersion>")) { content = content.Replace("<LangVersion>9.0</LangVersion>", "<LangVersion>10.0</LangVersion>"); File.WriteAllText(csprojFile, content); Debug.Log($"[CsprojVersionMonitor] Fixed LangVersion in: {Path.GetFileName(csprojFile)}"); filesModified = true; } } catch (System.Exception ex) { Debug.LogWarning($"[CsprojVersionMonitor] Failed to fix {Path.GetFileName(csprojFile)}: {ex.Message}"); } } // 如果修改了文件,刷新 Assets 文件夹 if (filesModified) { AssetDatabase.Refresh(); } } }omnisharp.json 用于IDE设置语言版本
{ "RoslynExtensionsOptions": { "EnableAnalyzersSupport": true, "LanguageVersions": { "csharp": "10.0" } }, "FormattingOptions": { "enableEditorConfigSupport": true } }