我试图在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));
}
这可以做或有没有更好的办法?
谢谢,你的解决方案真的帮助我。它不仅解决了当前的问题,而且还为我解决了大量的想法提供了方法。 –