c# - 带有泛型的 Unity3D GetComponent

标签 c# generics unity3d

我想编写一个 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/

相关文章:

c# - 为 UIBarButtonItem 添加/删除 EventHandler

c# - A* 寻路算法并不总能找到最短路线 C# XNA

java - 如何在静态泛型工厂方法中避免 "Type mismatch"?

c# - 为什么我的线条渲染器没有出现在 Unity 2D 中

c# - Unity3D:如何确定游戏对象的角以根据它定位其他游戏对象?

c# - ListView 打开目录

c# - C# 中的静态泛型方法

java - 如何绕过java泛型类型检查

c# - 初始化从单一行为派生的对象的最佳方法是什么?

c# - 有什么方法可以将我的 C# 项目添加为 IronPython/IronRuby 中的引用吗?