Created
January 8, 2022 01:14
-
-
Save D4KU/e1bcf1bd97219f588140169a691dd653 to your computer and use it in GitHub Desktop.
Unity File Watcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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