How to Activate and Deactivate gameobject on keypress

How to Activate and Deactivate gameobject on keypress

To activate or deactivate a game object on key press in Unity, you can use the Input.GetKeyDown() function to detect when the key is pressed and the GameObject.SetActive() function to set the active state of the game object. Here is an example of how you could do this in a script:



public GameObject objectToActivate; // Drag the object to activate in the Inspector
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        objectToActivate.SetActive(!objectToActivate.activeSelf);
    }
}

This script will toggle the active state of the objectToActivate game object whenever the space key is pressed.

You can also use the Input.GetKey() function to check if a key is being held down, or the Input.GetKeyUp() function to detect when a key is released.

if (Input.GetKey(KeyCode.Space))
{
    // Key is being held down
}

if (Input.GetKeyUp(KeyCode.Space))
{
    // Key was just released
}

You can replace KeyCode.Space with any other key code to detect different keys. You can find a list of all the available key codes in the Unity documentation.

..