Reputation: 11
I want to disable a GameObject, for achieving this I have written a code like this:
GameObject go;
go = GameObject.FindWithTag("MainCamera");
Destroy(go);
Then I am struggling to enable that disabled GameObject.
Could anyone help me on this regard?
Upvotes: 0
Views: 11504
Reputation: 7346
When calling Destroy
, you .... destroy the gameobject, you don't disable it. Instead, use SetActive.
Moreover, avoid using functions like FindXXX
, especially multiple times. Add a reference in the inspector instead
// 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();
}
Else, find the object once, either in the start function or when you try to disable the gameobject. Keeop in mind that FindXXX
functions can't find disabled gameobject (most of the time)
// 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();
}
Upvotes: 2
Reputation: 328
Duplicate question But .....
https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
Tip:
go.SetActive(!go.activeInHierarchy); // Toggle gameobject.
go = GameObject.FindWithTag("TADA") // Better
Upvotes: 1