Creating instance of class from System.Type variable

I'm trying to build up a simple game engine in XNA much inspired by Unity. What I'm currently working on is Components that can be attached to gameobjects. I have classes like "PlayerController" and "Collider" that are components and therefor inherits from the Component class.

I'm trying to create methods than can add a new component depending on a Type argument, for example when trying to require a component:

public void RequireComponent(System.Type type)
{
    //Create the component
    Component comp = new Component();
    //Convert the component to the requested type
    comp = (type)comp; // This obviously doesn't work
    //Add the component to the gameobject
    gameObject.components.Add(comp);
}

For example, the rigidbody component needs the gameobject to have a collider, so it requires the collider component:

public override void Initialize(GameObject owner)
{
    base.Initialize(owner);

    RequireComponent(typeof(Collider));
}

Can this be done or is there a better way?


public void RequireComponent(System.Type type)
{
    var comp = (Component)Activator.CreateInstance(type, new object[]{});

    gameObject.components.Add(comp);
}

However, if you find yourself passing in compile time constants, for example typeof(Collider) , you might as well do this:

public void Require<TComponent>() where TComponent : class, new()
{
    gameObject.components.Add(new TComponent());
}

and call it like this:

Require<Collider>();

instead of the first version:

RequireComponent(typeof(Collider));

To answer your question, the easiest way to get an object when given a Type object is to use the Activator class:

public void RequireComponent(System.Type type)
{
    var params = ; // Set all the parameters you might need in the constructor here
    var component = (typeof(type))Activator.CreateInstance(typeof(type), params.ToArray());
    gameObject.components.Add(component);
}

However, I'm thinking this might be a XY problem. From what I understand, this is your solution for achieving modularity in your game engine. Are you sure however that this is how you want to do it? My recommendation is for you to take some time and read up on polymorphism and related concepts, and how those can be applied in C#, before deciding on your approach.

链接地址: http://www.djcxy.com/p/95526.html

上一篇: 我如何转发声明一个内部类?

下一篇: 从System.Type变量创建类的实例