- Home /
How do I disable a key on the keyboard when it enters its fuction?
I have a simple question. How would i disable a button on a keyboard when it enters the function
DisableKey()
{
// What is the correct code to disable the "X" key on the keyboard?
}
Like for example once it hits game over i want to have the player not to be able to fire with the x button and i want to do it by simply disabling the X keystroke. Im sure there are other ways of not letting the player fire but I would like to learn how to do it by simply make sure if the player hits the X it doesnt work anymore. Im trying to learn new things :) Thanks again.
Can you give more details of what exactly you are trying to do? I might be able to help.
Answer by Hellium · Mar 01, 2019 at 05:04 PM
You can't "disable a key on the keyboard". What you have to do is to decide whether you run code when the key is pressed or not.
I would have done this using a Dictionary
and custom functions:
// At the top of your script
using System.Collections.Generic;
// In your class
private Dictionary<KeyCode, bool> keys = new Dictionary<KeyCode, bool>();
private bool GetKeyDown( Keycode keyCode )
{
if( !keys.ContainsKey( keyCode )
keys.Add( keyCode, true );
return Input.GetKeyDown( keyCode ) && keys[keyCode];
}
// Do the same for GetKey and GetKeyUp
private void DisableKey( KeyCode keyCode )
{
if( !keys.ContainsKey( keyCode )
keys.Add( keyCode, false );
else
keys[keyCode] = false;
}
private void EnableKey( KeyCode keyCode )
{
if( !keys.ContainsKey( keyCode )
keys.Add( keyCode, true );
else
keys[keycode] = true;
}
Then, instead of calling Input.GetKeyXXX( ... )
, call GetKey( ... )
You could also have these functions (and dictionary) in a static class in order to have a global manager like Unity's Input
class.
Well thank you so much at least have learned that I cannot disable a key on the keyboard. Thank you so much for your input. I definitely learned something new today :)
Also, if this has answered your question, go ahead and mark it as the solution so that the thread can be closed. :-)
A few disparities with keycode
, keyCode
, and key code
for folks planning to copy / paste, btw.
I've fixed those cases ^^.
Note that keys[keycode] = true;
does also work if the key doesn't exist yet in the dictionary. So the Enable / Disable method could look just like this:
private void Disable$$anonymous$$ey( $$anonymous$$eyCode keyCode )
{
keys[keyCode] = false;
}
private void Enable$$anonymous$$ey( $$anonymous$$eyCode keyCode )
{
keys[keycode] = true;
}
$$anonymous$$y bad, I wrote it from my phone and I've surely missed some mistakes made by the auto correct.
@Bunny83, I could not remember if the assignment could be done directly this way. Thanks for the re$$anonymous$$der!