How to set a condition to enable 'GetKeyDown'

I’m writing script which sets a condition to enable GetKeyDown. The condition is that the player needs to collide with a particular Game Object, and once they have done that then they will be able to press the spacebar to make an image appear. Prior to this I wrote a script which made the image appear as soon as the player collided with a Game Object which worked perfectly but now that I’ve added GetKeyDown into the mix it hasn’t worked.

The error message ‘Input.GetKeyDown(KeyCode)’ is a method, which is not valid in the given context’ also appeared.

I’ve inserted the code below. Thanks in advance! :slight_smile:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ArtworkAppear : MonoBehaviour

// This script sets a condition which only allows GetKeyDown("space") once they have collided with another game object

  { [SerializeField] private Image customImage;
 
   // Player needs to 'collect' item to enable interacting with a different game object
    void OnTriggerEnter (Collider other)
    {
        //If player collides with the item (collects it) interaction with another game object is enabled
        if (other.CompareTag ("Player"))
        {
           Input.GetKeyDown.enabled=true; //Now that the player has collided with the game object 'GetKeyDown' is enabled for the next interaction
        }

        if (Input.GetKeyDown("space")) //Now that GetKeyDown is enabled, once pressed a custom image appears
        {
            customImage.enabled = true;
        }
    }
  }

There’s several steps to this. Generally:

  • detect presence within the trigger (such as how you are doing)

  • set or clear a “within trigger” boolean to properly track being within the trigger

  • in your Update() loop:

—> when within trigger is true, check Input.GetKeyDown()
—> if true then tell the door to open / close

NOTE: as per the docs, Input.GetKeyDown() is ONLY valid in the Update() method or functions called directly from Update().

You can find specifics on all of the above steps in just about any Unity door open tutorial on Youtube.

1 Like

You’ll need to look into the difference between “methods” (a.k.a. “functions”) and “variables” in code. Once you understand that, the error message pretty much tells you what you need to know. Basically, “Input.GetKeyDown.enabled” isn’t a thing that makes sense, you’ll need your own variable.

Also, as Kurt has already touched on, it may be worth looking into the difference between Input.GetKeyDown(…), Input.GetKey(…), etc.

1 Like

Thank you! This worked :slight_smile: