Skip to content

Commit dc97d57

Browse files
committed
fix: when using VS Code, C# project file is not modified in Unity 2021 or later
1 parent a623bcf commit dc97d57

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Editor/CSharpProjectModifier.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System;
12
using System.IO;
23
using System.Linq;
34
using System.Text.RegularExpressions;
@@ -106,5 +107,61 @@ private static string AddRuleSet(string content, string ruleset)
106107

107108
private const string NewLine = "\r\n";
108109
private const string AdditionalContentComment = "<!-- C# Settings For Unity -->";
110+
111+
#if UNITY_2021_1_OR_NEWER
112+
private static FileSystemWatcher _watcher;
113+
114+
private static void OnCSProjectCreated(string file)
115+
{
116+
if (string.IsNullOrEmpty(file) || Path.GetExtension(file) != ".csproj" || !File.Exists(file))
117+
return;
118+
119+
//
120+
var codeEditor = Unity.CodeEditor.CodeEditor.Editor.CurrentCodeEditor;
121+
if (codeEditor?.GetType().Name != "VSCodeScriptEditor")
122+
return;
123+
124+
try
125+
{
126+
var text = File.ReadAllText(file, System.Text.Encoding.UTF8);
127+
var beforeHash = text.GetHashCode();
128+
text = OnGeneratedCSProject(file, text);
129+
var afterHash = text.GetHashCode();
130+
if (beforeHash != afterHash)
131+
{
132+
Logger.LogInfo("<color=orange>Modify CSProject</color> {0}", Path.GetFileName(file));
133+
File.WriteAllText(file, text);
134+
}
135+
}
136+
catch (Exception e)
137+
{
138+
UnityEngine.Debug.LogException(e);
139+
}
140+
}
141+
142+
[InitializeOnLoadMethod]
143+
private static void WatchCSProject()
144+
{
145+
#if !UNITY_EDITOR_WIN
146+
Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "enabled");
147+
#endif
148+
var resultDir = Path.GetFullPath(".");
149+
foreach (var file in Directory.GetFiles(resultDir, "*.csproj"))
150+
EditorApplication.delayCall += () => OnCSProjectCreated(Path.Combine(resultDir, file));
151+
152+
_watcher?.Dispose();
153+
_watcher = new FileSystemWatcher()
154+
{
155+
Path = resultDir,
156+
NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite,
157+
IncludeSubdirectories = false,
158+
EnableRaisingEvents = true,
159+
Filter = "*.csproj",
160+
};
161+
162+
_watcher.Created += (s, e) => EditorApplication.delayCall += () => OnCSProjectCreated(e.FullPath);
163+
_watcher.Changed += (s, e) => EditorApplication.delayCall += () => OnCSProjectCreated(e.FullPath);
164+
}
165+
#endif
109166
}
110167
}

0 commit comments

Comments
 (0)