2014-02-06 54 views
1

我試圖理解GetComponent,但我很難弄清楚如何編寫語法。我有兩個腳本(SpawnBehaviour和SpotClicked),並希望得到來自「SpawnBehaviour的布爾到SpotClicked。如何使用GetComponent-語法

如何獲得語法正確,並更改SpawnBehaviour布爾爲真?

void OnMouseDown() 
{ 
     screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); 
     offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)); 

    if(this.gameObject.tag == "fishSpot"){ 
      Debug.Log("Clicked "+gameObject.name); 
      //get "stopped"bool from "SpawnBehaviour" script and set it to true 
      SpawnBehaviour sb = spawnPoint.GetComponent<SpawnBehaviour>().stoppedSpawn=true; 
    } 
} 

在SpawnBehaviour.cs我有

public bool stoppedSpawn = false; 

回答

2

不幸的是the documentation不顯示你在C#中的例子,但它非常直截了當。

什麼你最終做的是一樣的東西

SpawnBehavior sb = gameObject.GetComponent<SpawnBehaviour>(); 
SpotClicked sc = gameObject.GetComponent<SpotClicked>(); 
//Do whatever you want with the variables from either MonoBehaviour 

還有the non-generic version

SpawnBehaviour sb = (SpawnBehaviour) gameObject.GetComponent(typeof(SpawnBehaviour)); 

但是,嘿,如果你能夠節省一些按鍵和管型,何樂而不爲。

當然,如果您要多次訪問它們,您可以將這些組件緩存在您的Start()中。調用GetComponent是很昂貴的,特別是如果你最終每幀都是這樣做的。

並且當你想設置一個布爾變量爲true SpawnBehaviour,你會做

SpawnBehaviour sb = gameObject.GetComponent<SpawnBehaviour>(); 
sb.stoppedSpawn = true; 

,或者如果你不小心保持SpawnBehaviour周圍,你可以做

gameObject.GetComponent<SpawnBehaviour>().stoppedSpawn = true; 

但是,如果您在其他地方需要它,或經常需要它,請將其緩存。

+0

我不斷地收到「不能隱式輸入'bool'到'spawnBehaviour' – Eyrik

+0

因此,讓我看看你正在使用的代碼,將它編輯到你的問題中 – Bart

+0

已更新我的代碼 – Eyrik

2

從概念上講,你應該先了解什麼是一個組件,什麼是遊戲物體,那麼它是不是很難得到語法正確:

enter image description here

例如:

var layer = someGameObject.GetComponent<GUILayer>();