I'm trying to generate code on changes using file watchers:

        private static void WatchPathAndExecute(string filePathToWatch, Action task)
            var pathSegments = filePathToWatch.Split('/');
            var justFileName = pathSegments[pathSegments.Length - 1];
            var dirSegments = (new List<string>(pathSegments)).GetRange(0, pathSegments.Length - 1);
            string path = Application.dataPath + String.Join("/", dirSegments);
            FileSystemWatcher watcher = new FileSystemWatcher(path, filter: justFileName);
            watcher.EnableRaisingEvents = true;
            watcher.Changed += ((sender, args) =>
                var o = new Object();
                EditorCoroutineUtility.StartCoroutine(DelayedTask(task, o, filePathToWatch), o);

        private static IEnumerator DelayedTask(Action task, Object o, string filePathToWatch)
            // AssetDatabase.ImportAsset("Assets"+filePathToWatch);
            yield return new EditorWaitForSeconds(.5f);

The issue is that it keeps running my generator on how the file WAS rather than what it's changed to.

Any ideas?

  • \$\begingroup\$ This looks like a XY-Problem to me. I am not exactly sure what you are trying to achieve. But I am pretty sure there is a better way to do that than using the FileSystemWatcher API. Probably something Unity-Specific like OnValidate or a custom build pipeline. Can you take a step back and explain the actual problem you are trying to solve? \$\endgroup\$
    – Philipp
    Commented Sep 20, 2021 at 12:21
  • \$\begingroup\$ @Philipp great idea, let's back up: I'd like to generate c# code for Unity which can utilize reflection on classes within my existing code. e.g. I want to find all the methods tagged with the GenerateHelperAttribute on subclasses of BaseClass and then build helper methods which call them. I realize there are alternatives for that specific problem, like writing a custom parser. I know there are solutions such as t4 as well, but I'd like my generator to have access to Unity objects in response to code changes. \$\endgroup\$
    – pixelpax
    Commented Sep 20, 2021 at 23:56
  • \$\begingroup\$ A real example is generating code that converts a NetworkBehaviour as a SerializedScriptableObject by just copying each field (but I'd like to solve the problem generally) \$\endgroup\$
    – pixelpax
    Commented Sep 20, 2021 at 23:58


You must log in to answer this question.

Browse other questions tagged .