2014-02-26 25 views
4

這應該是輕鬆的一年:團結/ C#查找對象並獲取組件

GameObject myCube = GameObject.Find("Cubey").GetComponent<GameObject>(); 

剛剛踢了錯誤CS0309:類型UnityEngine.GameObject必須轉換爲UnityEngine.Component爲了使用它作爲參數T IN一般類型或方法UnityEngine.GameObject.GetComponent()

通常的誤差統一顯示器是有用的,但是這僅僅是混亂。立方體不是GameObjects?任何指針將不勝感激(沒有雙關語意)。

+0

這可能是組件不是'GameObject's - 你試圖將'GetComponent '的值賦給'GameObject' - 當然你想要一個'GameComponent'或者'Component'(或者其他等價物統一) – Charleh

回答

3

那是一個容易犯的錯誤,一直沒有結果..太多次實際上:)

我會解釋它像對此,裸心中總有一種可能性,我錯了,或者誤解了這個問題:)

遊戲對象是一種類型。所以類型GameObject只能與GameObjects或從GameObject繼承的東西相關聯。

那這意思是:遊戲對象變量只能指向GameObjects和遊戲對象的子類。下面的代碼實際上是指向一個類型爲GameObject的Component。

GameObject.Find("Cubey").GetComponent<GameObject>(); 

這意味着找到Cubey並指向連接到Cubey的GameObject。

我猜前面已經說了上面的組件您正在尋找的是類型遊戲對象的不是。

如果你想變遊戲物體myCube指向Cubey你可以這樣做:

GameObject myCube; 

void Start(){ 
    // Lets say you have a script attached called Cubey.cs 
    // This is a slow approach 
    myCube = GameObject.FindObjectOfType<Cubey>(); 
} 

// A faster approach is to do 
// You need to then attach cubey through the inspector 
public GameObject myCube; 

希望幫助用戶來這個帖子同樣的問題。

9

GameObject不是組件。 A GameObject附有一束Component

你可以拿走的GetComponent呼叫,只需使用你的Find("Cubey")

GameObject myCube = GameObject.Find("Cubey");