When you are using AOP you should ever notify AOP framework when your assemblies are changed. While Unity doesn’t provide any API to handle script compilation done, you can use this code to do so.
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
[InitializeOnLoad]
static class AssemblyPostProcessor
{
//Keep list of watchers to prevent GC collect
static public List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
static AssemblyPostProcessor()
{
Debug.Log("Init AssemblyPostProcessor");
RigisterOnFileChanged(Application.dataPath + "/../Library/ScriptAssemblies/Assembly-CSharp.dll", DoInject);
}
static void DoInject(string path)
{
Debug.Log("Inject dll " + path);
//Inject code here...
Debug.Log("Inject dll Done");
}
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
};
fileSystemWatcher.Changed +=
(o, e) =>
{
Debug.Log("File changed:" + e.FullPath);
if(Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
{
action(path);
}
};
watchers.Add(fileSystemWatcher);
}
}
Hi, I’m very interested in AOP in Unity. I tried Postsharp and SNAP but failed to make them work. Actually Postsharp work well if I build my classes into a separate dll and import that dll into Unity. But I want to be able to use AOP without implementing separate dlls.
In your example, you showed how to catch the dll built by Unity but you didn’t actually show how to inject code into it and how to implement a real AOP solution.
Do you have any more examples about method intercepting and implementing aspect attributes?
My first AOP goal is to implement parameter validation on methods via an attribute. Do you think you can help me?
@PrefabEvolution , I just study this recently, but I didn’t realize it in unity3d. Do you have more demo code? Thanks. @Xtro , Can you share me your example code? My email: 1150987263@qq.com. Thanks.
I just make it in VS without U3D. And you said, you succeed by building the classes in Dll and then using it in U3D. So can you share me this detail method or show me the example code? Thanks.
Thanks very much, but there’s a problem here for I misunderstood your words.
I thought you imported the compiled U3D Dlls into vs, and did the static injection there, then finally imported back to U3D…
And if you have any progress on this topic, give me a message please, thanks, I will keep concern.