简体   繁体   English

Unity3D GetComponent with Generics

[英]Unity3D GetComponent with Generics

I want to write a util method to obtain a component on a given game object. 我想编写一个util方法来获取给定游戏对象的组件。 it looks like this ... 它看起来像这样......

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

The problem is with GetComponent ! 问题出在GetComponent How can i use the generic T with it so that it understand it? 我如何使用它的通用T ,以便它理解它? <typeof(T)> doesn't work, neither does GetComponent(T) or GetComponent(typeof(T)) . <typeof(T)>不起作用, GetComponent(T)GetComponent(typeof(T))也不起作用。

use the where clause, and fix your return to be Component 使用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;
}

Also the name of your method is a little misleading... your not really assigning the component, your just retrieving one that already exists. 你的方法的名称也有点误导......你没有真正分配组件,你只是检索已经存在的组件。 perhaps you meant to do this: 也许你打算这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM