Skip to content

Instantly share code, notes, and snippets.

@D4KU
Created January 8, 2022 01:14
Show Gist options
  • Select an option

  • Save D4KU/e1bcf1bd97219f588140169a691dd653 to your computer and use it in GitHub Desktop.

Select an option

Save D4KU/e1bcf1bd97219f588140169a691dd653 to your computer and use it in GitHub Desktop.
Unity File Watcher
// Adapted from
// https://forum.unity.com/threads/editor-compile-in-background.627952/#post-6989918
using System.IO;
using System.Threading;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Refreshes Asset Database as soon as file change was detected in
/// watched (sub-)directory.
/// </summary>
[InitializeOnLoad]
public static class FileWatcher
{
const string WATCH_PATH = "/Projects/Comment";
static bool refresh;
static FileWatcher()
{
ThreadPool.QueueUserWorkItem(SetupWatcher, Application.dataPath + WATCH_PATH);
EditorApplication.update += RefreshAssets;
}
static void OnChangeDetected(object sender, FileSystemEventArgs e)
{
refresh = true;
}
static void SetupWatcher(object state)
{
var watcher = new FileSystemWatcher()
{
Path = (string)state,
IncludeSubdirectories = true,
EnableRaisingEvents = true,
};
watcher.Changed += OnChangeDetected;
watcher.Created += OnChangeDetected;
watcher.Renamed += OnChangeDetected;
watcher.Deleted += OnChangeDetected;
}
static void RefreshAssets()
{
if (!refresh
|| EditorApplication.isCompiling
|| EditorApplication.isUpdating
|| EditorApplication.isPlayingOrWillChangePlaymode)
return;
AssetDatabase.Refresh();
refresh = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment