简体   繁体   中英

The type 'T' cannot be used as type parameter 'T' in the generic type or method

I have the following method:

protected T AttachComponent<T>(){
    T gsComponent = gameObject.GetComponent<T>();
    if(gsComponent == null){
        gsComponent = gameObject.AddComponent<T>();
    }
    return gsComponent;
}

On the AddComponent line I am getting the following error:

The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'. There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'.

I am not sure what I can do to fix this error, why Can I not do this?

The issue is that the AddObject method returns a Component . You need to tell the compiler that your T is actually a type of Component.

Attach a generic constraint to your method, to ensure that your T s are Component s

protected void AttachComponent<T>() where T : Component
{
    // Your code.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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