2017-06-18 150 views
1

我试图在XNA中构建一个很受Unity启发的简单游戏引擎。我目前的工作是可以附加到gameobjects的组件。我有像“PlayerController”和“Collider”这样的类,它们是组件,因此继承自Component类。从System.Type变量创建类的实例

我试图创建方法试图需要一个组件时相比,可以增加取决于类型参数的新组件,例如:

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); 
} 

例如,刚体组件需要游戏对象有一个对撞机,所以它需要碰撞组件:

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

    RequireComponent(typeof(Collider)); 
} 

这可以做或有没有更好的办法?

回答

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

    gameObject.components.Add(comp); 
} 

但是,如果你发现自己传递的编译时间常数,例如typeof(Collider),您不妨这样做:

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

,并调用它像这样:

Require<Collider>(); 

而不是第一个版本:

RequireComponent(typeof(Collider)); 
+0

谢谢,你的解决方案真的帮助我。它不仅解决了当前的问题,而且还为我解决了大量的想法提供了方法。 –

1

要给予Type对象时使用Activator类回答你的问题,得到一个对象的最简单的方法:

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); 
} 

不过,我想这可能是一个XY problem。据我所知,这是您在游戏引擎中实现模块化的解决方案。你确定这是你想要做的吗?我的建议是,在决定采用何种方法之前,需要花点时间阅读多态和相关概念,以及如何将这些概念应用于C#。