Hi,
I’m trying to get an input from the “space” button, but it looks like it doesn’t take the input when I click.
Here’s my code:
else if (other.gameObject.tag == "RedDoor") {
if (redKey_canvas.enabled) {
print("entered the door with the key");
if (Input.GetKeyDown(KeyCode.Space)) {
print("Space clicked!);
//OPEN DOOR
other.gameObject.GetComponent<SpriteRenderer>().sprite = enterDoor;
redKey_canvas.enabled = false;
}
}
In the console, I get the “entered door with key” message, but when I press Space, nothing happens.
I’ve also tried to add an Axis to the Input Manager named “DoorEnter”, but it doesn’t work either…
Input.GetKeyDown needs to be called from the Update() function since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.
If you already have it in the Update() function, then try
What function is this code contained in? I’m guessing it’s something like OnTriggerEnter? That fires in a single frame in which you enter a trigger. And Input.GetKeyDown also fires in only a single frame in which you press a key.
So, do you really press the space bar key and enter the trigger at exactly the same 1/60th of a second?
The problem with most programmers is they never setup keybindings separate. Which is also why most AAA titles fail with allowing customizable inputs.
On your Main.cs(I use Master.cs) is where any single use functions should be declared and used(AudioManager, Inputs, GameState, etc…). So by setting every button/hotkey to give a static declaration, you don’t need to check keycode values within each script. You only check the status of the static variable when needed.
So in a nutshell, your code should look more like this:
else if (other.gameObject.tag == "RedDoor")
{
if (redKey_canvas.enabled)
{
print("entered the door with the key");
if (Main.spaceBarPressed)
{
print("Space clicked!);
}
//OPEN DOOR
other.gameObject.GetComponent<SpriteRenderer>().sprite = enterDoor;
redKey_canvas.enabled = false;
}
}
If you are unsure how to get to this stage of programming, please review my current posts/questions or view my profile and message me personally on discord.
However, if your if (redKey_canvas.enabled) is only used within one frame, good luck pressing the space bar within that time frame. You will need to set a state(bool/enum) in order to allow a new button press shortly after a function is called(if that’s what you mean to do).