1

How can I derive from a class through reflection? The following works for getting an existing instance and for creating a new instance of the class.

public class TreeViewSHWinstances {

    [MenuItem("Reflect/CreateSHWinstances")]
    static void Activate() {
        Main();
    }

    static void Main() {

        Assembly asm = typeof(UnityEditor.EditorWindow).Assembly;

        Type wndType = asm.GetType ("UnityEditor.SceneHierarchyWindow");

        // Grabs an existing instance if it exists and then sets the focus to it.
        EditorWindow exstWnd = EditorWindow.GetWindow (wndType);

        // Always create a new instance regardless if one already exists.
        EditorWindow newWnd = (EditorWindow)Activator.CreateInstance (wndType);
    }

}

This is what I actually want to do, but obviously the assembly is not yet loaded and when I have tried to acquire it form the above class I get an error that says it is not a Type even though I'm requesting wndType.

// THIS IS NOT INTENDED TO NOR DOES IT WORK.
public MySceneHierarchyWindow : UnityEditor.SceneHierarchyWindow {


}

My guess was to use Emit in some way, but I after experimenting with it I'm not sure it is the right direction.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
DrDecipher
  • 37
  • 5
  • 1
    It's not easy. See http://stackoverflow.com/questions/3862226/dynamically-create-a-class-in-c-sharp – Blorgbeard Jul 05 '16 at 22:39
  • As linked by @Blorgbeard, `Reflection.Emit` is the way to go. The involved functions are quite good documented in the msdn. When you know how a .Net assembly is structured its not a big problem. – thehennyy Jul 06 '16 at 07:07

0 Answers0