gpt4 book ai didi

c# - 从 System.Type 变量创建类的实例

转载 作者:行者123 更新时间:2023-11-30 15:18:14 25 4
gpt4 key购买 nike

我正在尝试在受 Unity 启发的 XNA 中构建一个简单的游戏引擎。我目前正在研究的是可以附加到游戏对象的组件。我有像“PlayerController”和“Collider”这样的类,它们是组件,因此继承自 Component 类。

我正在尝试创建可以根据 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);
}

比如rigidbody组件需要gameobject有collider,所以需要collider组件:

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

RequireComponent(typeof(Collider));
}

这可以做到还是有更好的方法?

最佳答案

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

关于c# - 从 System.Type 变量创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com