- Home /
instantiate an object of unknown type
I have the following list of types:
shapeTypes = new List<System.Type>();
shapeTypes.Add(typeof(ShapeA));
shapeTypes.Add(typeof(ShapeB));
both types ShapeA and ShapeB inherit from class Shape. Now, I want to use this list to create a new object of type either ShapeA or ShapeB
//get random shape type
int typesSize = shapeTypes.Count;
int typeRand = Random.Range(0, typesSize);
System.Type type = shapeTypes[typeRand];
Material material = GetRandomMaterial();
var newShape = (Shape)System.Activator.CreateInstance(type, material);
I get the following error:
MissingMethodException: Default constructor not found for type ShapeA System.RuntimeType.CreateInstanceMono (System.Boolean nonPublic) (at :0) System.RuntimeType.CreateInstanceSlow (System.Boolean publicOnly, System.Boolean skipCheckThis, System.Boolean fillCache, System.Threading.StackCrawlMark& stackMark) (at :0) System.RuntimeType.CreateInstanceDefaultCtor (System.Boolean publicOnly, System.Boolean skipCheckThis, System.Boolean fillCache, System.Threading.StackCrawlMark& stackMark) (at :0) System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic) (at :0)
ShapeA does have a contructor:
public ShapeA(Material color) : base(color)
{
//some stuff here
}
So I have a couple of questions. 1) how do I fix this? 2) is there a better way to do what I'm trying to do. What I'm trying to do is instantiate an object of an unknown type from a list of types.
Thank you.
Answer by sisse008 · Jan 24, 2021 at 05:00 PM
I found an answer to my first question. The error was that I was passing the argument to the constructor in the wrong way so It was overloading to the wrong type.
Material material = GetRandomMaterial();
object[] lstArgument = { material };
Shape s = (Shape)System.Activator.CreateInstance(type, lstArgument);
Your answer
