- Home /
create instance from reflected type
Hi!
I am using reflection to find all derived classes. I want to be able to add instances of classes in editor(im trying to make a behaviour tree), based on classes that are derived from Node class, but I dont know how to use found types for casting. I have tried generics, with the same outcome. Help please!
class Node
{
Node node;
}
class ActionNode : Node
{
}
class Test
{
System.Type[] types;
Node someNode;
void Start()
{
types = System.Reflection.Assembly.GetAssembly(typeof(Node)).GetTypes();
foreach(System.Type refType in types)
{
if(refType.IsSubclassOf(typeof(Node)))
{
someNode = ( ????? )System.Activator.CreateInstance(refType);
}
}
}
}
Answer by Kiwasi · Jun 21, 2014 at 09:14 PM
Convert.ChangeType is your friend here.
Umm, i am poking this thing from every angle, without any result. Could you elaborate on this? Because in every way I can think of(and tried), I still need to use some kind of type. Otherwise, Im getting cast errors(can't do Node from Object).
Your answer
![](https://koobas.hobune.stream/wayback/20220613152215im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can custom editors that are built using Reflection.Emit be used in the Unity Editor? 1 Answer
reflection propertyinfo.getvalue compiles fine but gives erros in editor 1 Answer
ObjectField functions ignoring parameter 1 Answer
2D Dynamic Reflections ReadPixel Issue 0 Answers
I need an Array of System.type[] from all of my ScriptableObjects scripts 0 Answers