Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Reflection.Emit for Editor classes

Discussion in 'Editor & General Support' started by Mephesto_Khaan, Nov 30, 2022.

  1. Mephesto_Khaan

    Mephesto_Khaan

    Joined:
    Jun 2, 2013
    Posts:
    47
    I am trying to use Reflection.Emit to generate Editor classes "on the fly" while I use the Editor.
    It simply generates (via inheritance) empty sub-classes of an UnityEditor.Editor class that overrides OnInspectorGUI for some scripts. The Assembly is not saved, but gets updated everytime the Scripts get updated.

    But for some reason it is not working. I imagine because I need to tag or the assembly to the Unity.Editor to pick it up. Any ideas?


    Here is a very stripped down version of my code:

    Code (CSharp):
    1. [UnityEditor.Callbacks.DidReloadScripts]
    2. private static foo()
    3. {
    4.     AppDomain domain = AppDomain.CurrentDomain;
    5.     AssemblyName assemblyName = new AssemblyName("AutoEditorAssembly");
    6.     //TODO: Probably here I need to do something with the Assembly Definition?
    7.     AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
    8.     ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
    9.     TypeBuilder editorClass = moduleBuilder.DefineType("EditorAssemblyTest", TypeAttributes.Public, typeof(AutoEditor));
    10.     editorClass.CreateType();
    11. }
    12.  
    I know Reflection.Emit does not work with AOT platform, but I am assuming it should work fine for Editor classes.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,713
    You can't use TypeBuilder to make anything derived from
    UnityEngine.Object
    .

    This is because it skips the part where it "tickles" the engine code itself (which is NOT C# and NOT part of your assemblies) to connect itself properly.

    UnityEditor.Editor is a ScriptableObject which is of course derived from a UnityEngine.Object.
     
    Mephesto_Khaan likes this.
  3. Mephesto_Khaan

    Mephesto_Khaan

    Joined:
    Jun 2, 2013
    Posts:
    47
    Thanks Kurt!
    That is unfortunate, time for plan B :)