2016-03-21 25 views
5

ho il seguente metodo:Il tipo 'T' non può essere utilizzato come parametro di tipo 'T' nel tipo generico o di un metodo

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

Sulla linea AddComponent sto ottenendo il seguente errore:

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

Non sono sicuro di cosa posso fare per correggere questo errore, perché non posso farlo?

+0

si sarebbe sicuramente farlo ** ** con un'estensione in C#. Ecco un tutorial per tutti i principianti che leggono http://stackoverflow.com/a/35629303/294884 Spero che aiuti! – Fattie

risposta

13

Il problema è che il metodo AddObject restituisce un valore Component. Devi dire al compilatore che il tuo T è in realtà un tipo di componente.

Fissare un vincolo generico per il metodo, per garantire che i T s sono Component s

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

Questo mi dà questo: 'GameObject' non è un vincolo valido. Un tipo usato come vincolo deve essere un'interfaccia, una classe non sigillata o un parametro di tipo. –

+0

@GetOffMyLawn Spiacente, ho letto male la tua domanda leggermente. Ho aggiornato il codice nel frattempo per chiarire la mia risposta. Si noti che il vincolo è ora su 'Component', non' GameObject' (errore mio) –

+0

Nessun problema! Potresti spiegare per cosa è la parte "where"? –

Problemi correlati