Serializing Mono.Cecil Injected Fields

I’m working on updating my asset to make it simpler to use by automatically injecting fields into MonoBehaviour objects using Mono.Cecil. Playing around to prove the concept I’ve managed to inject a basic primitive type field that does show up in the inspector, but I’ve noticed that any value assigned does not survive the serialization/deserialization process after Unity recompiles Assembly-CSharp.dll after modifying a script.

Does anybody know of a way to modify Assembly-CSharp.dll after Unity has recompiled it but before it deserializes?

Related question: Is the assembly load order in Unity fixed, and what is the load order (more specifically, are assemblies that are in the Assets folder loaded before or after Assembly-CSharp.dll and Assembly-CSharp-Editor.dll)?

Many thanks!

  1. You can catch system file modification event like this
        static object locker = new object();
        static public void RigisterOnFileChanged(string path, System.Action<string> action)
        {
            Debug.Log("Watch: " + Path.GetFullPath(path));
            var fileSystemWatcher =
                new FileSystemWatcher(Path.GetDirectoryName(path)) {
                    EnableRaisingEvents = true,
                };

            FileSystemEventHandler par = null;
            par = (o, e) =>
            {
                lock (locker)
                {
                    Debug.Log("File changed:" + e.FullPath);
                    if (Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
                    {
                        fileSystemWatcher.Changed -= par;
                        fileSystemWatcher.Created -= par;
                        action(path);
                    }
                }
            };
            fileSystemWatcher.Created += par;
            fileSystemWatcher.Changed += par;
            watchers.Add(fileSystemWatcher);
        }

In that way you can catch when dlls changed, but i can’t guaranty that unity can’n load this assemblies before you inject into it.
The only working way to identify when unity build dlls its replace Mono compeller with binaries that will catch arguments, run wrapped compiler with input arguments and send event to make the injection.

Oh hey, a reply! I’ve already gone with a manageable compromise for my purposes, but this looks promising for possible future uses. So thanks for the interesting, albeit a bit belated, reply.
Cheers mate!