- Home /
activating and deactivating gameObject on keypress?
bit of a noob when it comes to scripting with c# but want to know if there is an easy way to instantiate an object on getkey down. So a shield and then when I let go of shift the object will be disappear and to be able to repeat this step
Answer by TheIvan1928 · Sep 17, 2017 at 11:05 AM
There's a big difference between instantiating and enabling/disabling a Game Object.
In your case, GameObject.SetActive() is the method you want to use.
First, you declare a GameObject field:
public GameObject shieldObject;
And then, on a function that ocurrs every frame (i.e. the Update () method):
if (Input.GetKeyDown(KeyCode.LeftShift))
shieldObject.SetActive(true);
else if (Input.GetKeyUp(KeyCode.LeftShift))
shieldObject.SetActive(false);
This will enable the shield object whenever the player starts pressing shift, and disable it when the user stops holding it.
You could also do the same thing with Object.Instantiate(), but it would require some more unnecessary work.
What if I want to toggle between them? Escape key brings the menu up, but hitting it again closes the menu?
if (Input.GetKeyDown(KeyCode.Escape))
yourObject.SetActive(!yourObject.activeSelf);
Your answer
Follow this Question
Related Questions
Deactivate an object - and all scripts in that object deactivated? 1 Answer
activate object on key press only, otherwise always deactivated! 2 Answers
Turning off rigidbody without turning the entire object inactive? 1 Answer
Having a game object de-activate itself 1 Answer
Children of DualTouchControls prefab keep being forced to active 0 Answers