2016-03-21 54 views
5

被用作類型參數「T」我有以下方法:類型「T」不能在通用類型或方法

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

AddComponent線我得到以下錯誤:

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'. 

我不知道我能做些什麼來解決這個錯誤,爲什麼我不能這樣做?

+0

你一定會做到這一點**,在C#中的擴展**。這裏是任何初學者閱讀http://stackoverflow.com/a/35629303/294884的教程希望它有幫助! – Fattie

回答

13

問題是AddObject方法返回Component。你需要告訴編譯器你的T實際上是一種Component。

連接通用約束你的方法,以確保您的T s爲Component小號

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

這給了我這個:'GameObject'不是一個有效的約束。用作約束的類型必須是接口,非密封類或類型參數。 –

+0

@GetOffMyLawn對不起,我誤解了你的問題。我在過渡期間更新了代碼,以澄清我的答案。請注意,該約束現在在'Component'上,而不是'GameObject'(我的錯誤) –

+0

沒問題!你能解釋一下「哪裏」部分的用途嗎? –

相關問題