Iam trying to create instances of classes by string names. Iam creating utility where user chose type from popup box of string (content of this field is content of field "types") and I need to create instance of class based on his choice. Unfortunatelly I totally dont know how to do it
class Parent
{
}
class Child1 : Parent
{
}
class Child2 : Parent
{
}
string[] types = { "Child1", "Child2" };
List<Parent> collection = new List<Parent>();
void Main()
{
Parent newElement = Activator.CreateInstance(this.types[0]) as Parent; // this row is not working :( and I dont know how to make it work
this.collection.Add(newElement);
if (this.collection[0] is Child1)
{
Debug.Log("I want this to be true");
}
else
{
Debug.Log("Error");
}
}
I finnaly make it work. Thank you all. Here is working code (problem was in missing namespace)
namespace MyNamespace
{ class Parent {
}
class Child1 : Parent
{
}
class Child2 : Parent
{
}
class Main
{
string[] types = { typeof(Child1).ToString(), typeof(Child2).ToString() };
List<Parent> collection = new List<Parent>();
public void Init()
{
Parent newElement = Activator.CreateInstance(Type.GetType(this.types[0])) as Parent;
this.collection.Add(newElement);
if (this.collection[0] is Child1)
{
Debug.Log("I want this to be true");
}
else
{
Debug.Log("Error");
}
}
}
}
namespacein your code, because that's what you are missing.