Referencing Game Objects to SetActive with KeyPress

To SetActive a game object in the OnClick with Unity’s Engine is easy, however if I want to reference an object to SetActive by a getkey function is impossible, because it just won’t come up in my editor.

Shouldn’t I be able to reference any game object in my scene? No matter what script or class I’m writing the script in?

it depends if you are trying to find a gameObject that’s inactive you won’t. so if you want to activate a gameObject by a KeyDown through code you’ll need a reference to that gameObject.

What does that mean?

Yes, of course. As @jister says, GameObject.Find won’t find inactive objects, but you can still reference them directly.

Wait… what other way of referencing it is there other than find?
I just want the object to become active when I hit the key

You could link it in the editor (inspector)

I think you can find scripts on inactive game objects, so you could have an activator script on all those game objects

Right, GameObject.Find is not the standard way of referencing an object. The standard way is: declare a public property of the appropriate type on your class; and in the Inspector for some object using your class, drag in a property of any type.

Watch pretty much any Unity tutorial, and I’m pretty confident you will see this technique applied. If you have an object in the scene that needs to refer to some other object in the scene, this is usually the best way to do it.

1 Like

Or if you want to stick to code. don’t set it inactive in the hierarchy. Get your reference with Find in void Awake() or so and then set it to inactive. then the reference will stay to the non active gameObject so you can set it active with your keyDown.

If I didn’t think I had to code this, I wouldn’t, but it seems that if I am toggling an object with a keyboard shortcut, I’ve got to write it in code.

is the Find option the
Item = gameObject.Find(“Object”); ?

Then using that Item instance to toggle it?

I think what everyone is referring to is to not use the find option because it will not locate an inactive object.

I think what you need to do is something like this. Lets say you have an object called the Big Alien Cannon.
On the script you want to use to activate the Big Alien Cannon you would make a public GameObject and reference the cannon. Then wake up the cannon using the object reference. No need to use the find option.

Example might be something like this.

public GameObject bigAlienCannon;

void Awake()
{
     bigAlienCannon.SetActive(false);
}

void Update()
{
     if (Input.GetKeyDown("space"))
     {
          bigAlienCannon.SetActive(true);
     }
}

This is not tested code and since I did it at lunch the syntax may not be correct, but I believe this is what the others are suggesting.

1 Like