2

I have a game object that at the beginning of the game is disabled. Then I want to enable it later via script. So far I have tried to use the following code:

GameObject.Find("name").SetActive (true); 

The problem is that as the game object at the beginning is disabled when I do

GameObject.Find("name") 

I get null. So I don't know how to activate it. It's a canvas.

3
  • 1
    Is the name definitely correct? Commented Jul 7, 2015 at 14:39
  • like rhughes mentions, you need to define name correctly. Commented Jul 8, 2015 at 7:11
  • Do you necessarily need to disable the GameObject? Could you just disable one of its components instead, such as a Renderer, Rigidbody, and/or Collider? Commented Jul 8, 2015 at 15:21

2 Answers 2

9

You can create a class variable in your script, and then in the Unity scene editor assign your disabled object to that class variable.

For example:

In your script file, create the class variable:

public GameObject objectToEnable; 

Then, in the scene editor, the "objectToEnable" variable will appear on the Script component of the object containing your script. Simply drag your disabled object to that variable (in the scene editor) to set the reference.

Once you do that, at runtime you can just do:

objectToEnable.SetActive(true); 

The reference should still be valid, even if the object is disabled.

Sign up to request clarification or add additional context in comments.

Comments

1

You could first save the object in a variable, for example you first declare a variable that will hold the object

 GameObject tempVar; //this line goes outside any function, not in Start or Update 

Then in the Start or Awake function you find the object and save it

 tempVar = GameObject.Find("name"); // this line goes in Start, just before you disable the object tempVar.SetActive(false); //now the object is disabled but saved in a variable with which you can access it at any time

Of course, this code assumes the object is NOT disabled before the game starts.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.