This may be multiple things I am asking for, but I think they all relate to reflection in some way.
I am making a visual scripting tool/node editor. I have a system setup already in code that upon opening an editor window saves a node script, then it can be loaded by another script on a gameobject and used. What I want to do is to automate future use when I start doing the GUI; as in, I don’t want to have to have a huge switch case or list that I have to add to every time I add a new node type.
I want to use reflection, or something, that will look for every class I make that extends from the abstract class ‘Node’ and can tell all of their properties and give me some way to make an instance of it on request. This way creating new node types is as simple as duplicating a basic existing one, changing the name and data, and the editor I coded does it for me.
How should I go about doing this? Google has not seemed to help me much XD
Just use this extension method:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class ReflectionHelpers
{
public static System.Type[] GetAllDerivedTypes(this System.AppDomain aAppDomain, System.Type aType)
{
var result = new List<System.Type>();
var assemblies = aAppDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsSubclassOf(aType))
result.Add(type);
}
}
return result.ToArray();
}
public static System.Type[] GetAllDerivedTypes<T>(this System.AppDomain aAppDomain)
{
return GerAllDerivedTypes(aAppDomain, typeof(T));
}
public static System.Type[] GetTypesWithInterface(this System.AppDomain aAppDomain, System.Type aInterfaceType)
{
var result = new List<System.Type>();
var assemblies = aAppDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes();
foreach (var type in types)
{
if (aInterfaceType.IsAssignableFrom(type))
result.Add(type);
}
}
return result.ToArray();
}
public static System.Type[] GetTypesWithInterface<T>(this System.AppDomain aAppDomain)
{
return GetTypesWithInterface(aAppDomain, typeof(T));
}
}
Just place this class somewhere in your project. Then just use:
var types = System.AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(YourBaseClass));
edit
I’ve just added the method “GetTypesWithInterface” which also works with interface types. So you can find all classes which implement a given interface.
var types = System.AppDomain.CurrentDomain.GetTypesWithInterface(typeof(IMyInterface));