Skip to content

Commit d38367a

Browse files
committed
Implement script reloading
1 parent a35b145 commit d38367a

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

ScriptLoader/ScriptLoader.cs

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,56 @@ public class ScriptLoader : BaseUnityPlugin
1515
{
1616
private readonly string scriptsPath = Path.Combine(Paths.GameRootPath, "scripts");
1717
private Dictionary<string, ScriptInfo> availableScripts = new Dictionary<string, ScriptInfo>();
18+
private FileSystemWatcher fileSystemWatcher;
1819
private Assembly lastCompilationAssembly;
1920
private string lastCompilationHash;
2021
private LoggerTextWriter loggerTextWriter;
22+
private bool shouldRecompile;
2123

22-
public void Awake()
24+
private void Awake()
2325
{
2426
DontDestroyOnLoad(this);
25-
2627
loggerTextWriter = new LoggerTextWriter(Logger);
28+
CompileScripts();
29+
30+
fileSystemWatcher = new FileSystemWatcher(scriptsPath);
31+
fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
32+
fileSystemWatcher.Filter = "*.cs";
33+
fileSystemWatcher.Changed += (sender, args) =>
34+
{
35+
Logger.LogInfo($"File {args.Name} changed. Recompiling.");
36+
shouldRecompile = true;
37+
};
38+
fileSystemWatcher.Deleted += (sender, args) =>
39+
{
40+
Logger.LogInfo($"File {args.Name} removed. Recompiling.");
41+
shouldRecompile = true;
42+
};
43+
fileSystemWatcher.Created += (sender, args) =>
44+
{
45+
Logger.LogInfo($"File {args.Name} created. Recompiling.");
46+
shouldRecompile = true;
47+
};
48+
fileSystemWatcher.Renamed += (sender, args) =>
49+
{
50+
Logger.LogInfo($"File {args.Name} renamed. Recompiling.");
51+
shouldRecompile = true;
52+
};
53+
fileSystemWatcher.EnableRaisingEvents = true;
54+
}
55+
56+
private void OnDestroy()
57+
{
58+
fileSystemWatcher.EnableRaisingEvents = false;
59+
fileSystemWatcher.Dispose();
60+
}
2761

62+
private void Update()
63+
{
64+
if (!shouldRecompile)
65+
return;
2866
CompileScripts();
67+
shouldRecompile = false;
2968
}
3069

3170
private void CompileScripts()
@@ -58,8 +97,9 @@ private void CompileScripts()
5897
scriptDict[scriptFile] = data;
5998
}
6099

61-
var hash = Convert.ToBase64String(md5.TransformFinalBlock(new byte[0], 0, 0));
62-
100+
md5.TransformFinalBlock(new byte[0], 0, 0);
101+
var hash = Convert.ToBase64String(md5.Hash);
102+
63103
if (hash == lastCompilationHash)
64104
{
65105
Logger.LogInfo("No changes detected! Skipping compilation!");

ScriptLoader/ScriptLoader.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
<HintPath>..\lib\mcs.dll</HintPath>
4141
<Private>False</Private>
4242
</Reference>
43+
<Reference Include="System" />
4344
<Reference Include="System.Core" />
4445
<Reference Include="UnityEngine">
4546
<HintPath>..\lib\UnityEngine.dll</HintPath>

0 commit comments

Comments
 (0)