BadmintonCat
BadmintonCat

Reputation: 9586

Unity3D GetComponent with Generics

I want to write a util method to obtain a component on a given game object. 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! How can i use the generic T with it so that it understand it? <typeof(T)> doesn't work, neither does GetComponent(T) or GetComponent(typeof(T)).

Upvotes: 1

Views: 4311

Answers (1)

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

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

Upvotes: 5

Related Questions