Activate gameobject that is deactivated with c#

Hi, I have a gameobject called Trees that have some trees inside, it begins inactive or I also can disable through this code in C#:

if(Input.GetKeyUp(KeyCode.Space)){         
   GameObject.Find("Trees").active = false;
}

But when i want to reactivate it with:

GameObject.Find("Trees").active = true;

unity can find the gameobject, is there a way to find it and activate it again?

14754-question.png

2 Answers

2

public GameObject Trees;

void Update(){
   if(Input.GetKey(KeyCode.Space)){
       Trees.SetActive(false);
   }
   else{
     Trees.SetActive(true);
   }
}

set trees in the inspector.

Thanks for your answer!! :D sorry but im new in this of unity :( how can i set trees in the inspector?

–

Drag your Trees GameObject into the serialized field Trees that will appear in the inspector. Example of a serialized field: [14757-serializedfield.png|14757] I realized I left out a brace in my code, I'll edit it.

–

Thanks for your help I found this solution foreach (GameObject go in GameObject.FindGameObjectsWithTag ("TreeTag")) { go.renderer.enabled = enabled; } Also work as you said :D

–

The way you are doing it doesn't disable the GameObject - it just makes it invisible. If you want to change whether it is enabled, use SetActive() with true or false.

–

Can you send an example? its cause when i try to reactivate an gameboject y cant be restore, i read in some places that after inactive unity wont recognize it

–

i need without public or serializable field

could you please help me for that

Try putting the key word [Serialize Field] above it.

–