gpt4 book ai didi

c# - 带有泛型的 Unity3D GetComponent

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:55 24 4
gpt4 key购买 nike

我想编写一个 util 方法来获取给定游戏对象上的组件。看起来像这样……

    public static MonoBehaviour FindAndAssignComponent<T>(string name)
{
GameObject g = GameObject.Find(name);
if (g != null) return g.GetComponent<T>();
return null;
}

问题出在GetComponent !我如何使用通用 T用它让它明白吗? <typeof(T)>不起作用,GetComponent(T) 也不起作用或 GetComponent(typeof(T)) .

最佳答案

使用 where 子句,并将返回值固定为 Component

public static Component FindAndAssignComponent<T>(string name) where T : Component
{
GameObject g = GameObject.Find(name);
if (g != null) return g.GetComponent<T>();
return null;
}

此外,您的方法名称有点误导...您并没有真正分配组件,您只是检索已经存在的组件。也许你打算这样做:

public static void FindAndAssignComponent<T>(string name) where T : Component
{
GameObject g = GameObject.Find(name);
if (g == null)
throw new ObjectNotFoundException(String.Format("GameObject '{0}' not found in hierarchy!", name));
g.AddComponent<T>();
}

关于c# - 带有泛型的 Unity3D GetComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678162/

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