2017-03-17 100 views
0

要禁用遊戲物體,實現這一目標我已經寫了這樣的代碼:我如何啓用禁用的遊戲對象,團結

GameObject go; 
go = GameObject.FindWithTag("MainCamera"); 
Destroy(go); 

然後我努力使殘疾遊戲物體。

任何人都可以在這方面幫助我嗎?

回答

2

當調用Destroy,你....破壞遊戲對象,您不要禁用它。相反,使用SetActive

此外,避免使用FindXXX等功能,特別是多次使用。添加引用的檢查,而不是

// Drag & Drop the gameobject in the inspector 
public GameObject targetGameObject ; 

public void DisableGameObject() 
{ 
     targetGameObject.SetActive(false) ; 
} 

public void EnableGameObject() 
{ 
     targetGameObject.SetActive(true) ; 
} 

public void ToggleGameObject() 
{ 
     if(targetGameObject.activeSelf) 
      DisableGameObject() ; 
     else 
      EnableGameObject(); 
} 

否則,找對象一次,無論是在啓動功能或當您嘗試禁用遊戲對象。 Keeop記住FindXXX功能無法找到禁用遊戲物體(大部分時間)

// Drag & Drop the gameobject in the inspector 
private GameObject targetGameObject ; 

public void DisableGameObject() 
{ 
     if(targetGameObject == null) 
      targetGameObject = GameObject.FindWithTag("MainCamera"); 
     if(targetGameObject != null) 
      targetGameObject.SetActive(false) ; 
} 

public void EnableGameObject() 
{ 
     if(targetGameObject != null) 
      targetGameObject.SetActive(true) ; 
} 

public void ToggleGameObject() 
{ 
     if(targetGameObject == null) 
      targetGameObject = GameObject.FindWithTag("MainCamera"); 

     if(targetGameObject == null) 
      return ; 

     if(targetGameObject.activeSelf) 
      DisableGameObject() ; 
     else 
      EnableGameObject(); 
} 
+0

如果標記MainCamera,就沒有必要進行搜索,使用Camera.main – Everts

+1

使用'遊戲對象的海​​報。 FindWithTag',因此,我也使用它。這是一般的方法。也許,他會改變主意,他會想找到一個帶有不同標籤的gameobject。 – Hellium