- Home /
How to find all classes deriving from a base class?
I am creating a custom editor window.
I want to find all classes that derive from a base class, and show them in my window.
"Find" similar to how you can use Resources.Load, but my base class does not derive from UnityEngine.Object so I need another way.
I have found several forums showing different ways of using Reflection to find all types that derive from a base type, but I don't understand how to use this.
https://answers.unity.com/questions/983125/c-using-reflection-to-automate-finding-classes.html
I don't know what to do with an array of Types.
How can I use that to get access to the actual classes?
Answer by IggyZuk · Oct 13, 2020 at 05:58 PM
You can create an instance of the class using the base type. Here is an example using LINQ.
IEnumerable<BaseClass> GetAll()
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => type.IsSubclassOf(typeof(BaseClass)))
.Select(type => Activator.CreateInstance(type) as BaseClass);
}
GetAll().ToList().ForEach(x => x.DoStuff());
Awesome! Just what I needed, thank you!
I found a lot of good reading about the Activator. Very useful tool!
Your answer
