Unity Read What Buttons Are Being Pressed
- Spaces
- Default
- Help Room
- META
- Moderators
-
- Topics
- Questions
- Users
- Badges
- Dwelling /
3
How to detect which key is pressed?
I am trying to determine which Keyboard key is pressed to use that in a switch argument, but apparently the code I attempt to use is non working. It was taken more than or less directly from the Script Reference, but 'Outcome.current' doesn't seem to find my keyboard strokes. When I print information technology to the condition bar, information technology says 'Null'.
var pressKey; var dirEvent : Outcome = Effect.current; if(dirEvent.isKey) { pressKey = dirEvent.keyCode; }
7 Replies
· Add your reply
- Sort:
30
Answer past jamesflowerdew · Apr 08, 2022 at 01:27 PM
foreach(KeyCode vKey in Arrangement.Enum.GetValues(typeof(KeyCode))){ if(Input.GetKey(vKey)){ //your code here } }
:) this detects what central has been pressed. I use it for my custom input manaer.
This is slick... thank you for sharing!
@jamesflowerdew If you would not $$bearding$$d, could please explain to me how this works? I inquire not out of doubt of the answer's validity, but only in an endeavour to empathize this confounding lawmaking.
@$$anonymous$$derbuns information technology's been a year but for anyone else who might want an explanation: The line
foreach($$anonymous$$eyCode v$$anonymous$$ey in System.Enum.GetValues(typeof($$anonymous$$eyCode)))
Iterates over every $$bearding$$eyCode in the System. Organisation.Enum.GetValues(typeof($$bearding$$eyCode)) gets every enum value of type $$anonymous$$eyCode as an assortment.
The body of the foreach loop just checks if our current value 'v$$anonymous$$ey' is currently pressed. The loop performs this bank check for every possible value of '5$$anonymous$$ey.'
Its 2022 and I see people still Brute forcing their manner out. GG :D
2
Answer by mcarriere · Sep 12, 2011 at 04:54 PM
Your question doesn't requite as well much information, just here are a few options:
If yous are absolutely tied to using a switch statement to iterate through your keys, yous could do something like this:
var myKeys : Assortment; function Commencement() { myKeys = new Array(); myKeys.Add(KeyCode.W); myKeys.Add(KeyCode.S); myKeys.Add(KeyCode.A); myKeys.Add(KeyCode.D); } part Update () { for (var key : KeyCode in myKeys) { if (Input.GetKeyDown(cardinal)) { switch (key) { case KeyCode.W: Debug.Log("Due west!"); suspension; instance KeyCode.Southward: Debug.Log("Southward!"); break; case KeyCode.A: Debug.Log("A!"); suspension; example KeyCode.D: Debug.Log("D!"); break; } } } }
However, it would probably be slightly cleaner if y'all did this:
if (Input.GetKeyDown(KeyCode.W)) { } if (Input.GetKeyDown(KeyCode.S)) { } if (Input.GetKeyDown(KeyCode.A)) { } if (Input.GetKeyDown(KeyCode.D)) { }
Change the sequent "if"southward to "else if" if you only want 1 input to work at a time. Change "GetKeyDown" to "GetKey", if yous desire it to recognize the input every frame.
If you had read all the comments added to the original questions, yous would take had more information, including the 'if(Input.Getkey)' variant.
The loop would be an idea, but I think I stay with the current version. The default value of the switch would accept been handy, but I simply placed the default value into the variable before all the if statements, so it gets overridden, when a valid key is pressed, and stays the aforementioned, if some other key is pressed.
But thanks anyway.
If anyone is interested, here is the current script (-snippet).
function plDirection () { statics.plHeading = Vector2(0, 0); if(Input.Get$$bearding$$ey ($$anonymous$$eyCode.G)) { statics.plHeading = Vector2(1, 0); } if(Input.Become$$bearding$$ey ($$anonymous$$eyCode.D)) { statics.plHeading = Vector2(-1, 0); } if(Input.Go$$anonymous$$ey ($$anonymous$$eyCode.T)) { statics.plHeading = Vector2(0, 1); } if(Input.Get$$anonymous$$ey ($$bearding$$eyCode.R)) { statics.plHeading = Vector2(-1, 1); } if(Input.Get$$bearding$$ey ($$anonymous$$eyCode.V)) { statics.plHeading = Vector2(1, -ane); } if(Input.Get$$anonymous$$ey ($$bearding$$eyCode.C)) { statics.plHeading = Vector2(0, -ane); } }
I'm a bit dislocated, I only did a text search on the page, and this comment and my answer were the only ones to suggest using Input.Get$$anonymous$$ey(). Either way, glad you found a solution.
thanks for your explain. Change "Get$$anonymous$$eyDown" to "Become$$anonymous$$ey", if you desire it to recognize the input every frame. It helped me alot :)
ii
Answer past geniusprime · May 22, 2022 at 10:23 AM
The following code worked for me. It is based of of @jamesflowerdew. Firstly a KeyCode variable is created. This variable would store the custom central printing. The DetectInput() function captures the central input by the user and stores it in kCode. kCode is then used in the Input.GetKeyDown(KeyCode) function. With this approach y'all should be able to create an array or a series of KeyCode variables that have specified functions and theese KeyCode variables can be changed to any input key the user wants.
Then you will be able to create a
-
KeyCode jumpKCode
-
jumpKCode tin exist used in the following for you jump trigger
-
if( Input.GetKeyDown(jumpKCode))
-
{
-
Jump();
-
}
jumpKCode can be assign any key input. Hopefully this makes sense to anyone who is struggling with this.
private bool bDetectKey; private KeyCode kCode; //this stores your custom fundamental void Update () { if(Input.GetKeyDown(KeyCode.Render)) { if (bDetectKey) bDetectKey = false; else bDetectKey = truthful; } if(bDetectKey) //this detects the central existence pressed and saves it to kCode DetectInput(); if(Input.GetKeyDown(kCode)) //the kCode is so compared like a standard Input.GetKeyDown(KeyCode) boolean { impress("Custom primal worked"); } } public void DetectInput() { foreach(KeyCode vkey in Organisation.Enum.GetValues(typeof(KeyCode))) { if(Input.GetKey(vkey)) { if (vkey != KeyCode.Return) { kCode = vkey; //this saves the cardinal being pressed bDetectKey = false; } } } }
Fantastic, that was just what I needed! :)
Thank you lot!
0
Answer by Scenia · Jun 15, 2013 at 02:fifteen PM
Yous tin can avert using many ifs, just y'all can't avert using Input.GetKey(Down). The trick is the post-obit: switch(argument) compares the statement to each example. By using true equally the argument, you lot can use boolean statements as cases:
switch(truthful) { instance Input.GetKey("g"): statics.plHeading = Vector2(1,0); break; case Input.GetKey("d"): // and then on... default: // this way, you can still employ a default statement }
0
Answer past Maister · Mar 17, 2022 at ten:27 PM
The method described from Scenia does non piece of work for me. The compiler says, that after the "case"-statement has to be a constant value.
However I thought it would exist prissy having a dictionary with the push button name as primal and the part to call as value:
using System.Collections.Generic; using UnityEngine; private Dictionary<string, InputDelegate> myKeys; private delegate void InputDelegate(); private InputDelegate myTempDelegate; individual void start() { this.myKeys = new Lexicon<string, InputDelegate> (); this.myTempDelegate = Fire; myKeys.Add ("Fire1",myTempDelegate); this.myTempDelegate = Inventory; myKeys.Add ("Inventory",myTempDelegate); } individual Update() { if (Input.anyKeyDown) { foreach (var dic in this.myKeys) { if (Input.GetButtonDown (dic.Fundamental)) { dic.Value (); } } } } private void Fire() { //do all the stuff to fire } individual void Inventory() { //open up up the inventory }
Yous would demand to specify a key for the button "inventory" in the input director, since it is not in that location past default. This fashion, you lot keep your update method short and tidy, but get the key-function-binding department in the start method, which could get long, if yous are having many keys. For full general movement of a grapheme you should practise something like this:
private void FixedUpdate() { // read inputs float h = Input.GetAxis ("Horizontal"); float v = CrossPlatformInputManager.GetAxis("Vertical"); bool hunker = Input.GetKey(KeyCode.C); //do all the physics stuff... //... }
Anyway.. I estimate in terms of performance you could / (should?) stick with the method of having all the if (Input.GetKeyDown(...)) 's in the update method.
$$anonymous$$eep in $$anonymous$$d Unity works with different script languages, which have different rules. $$anonymous$$y solution is for JavaScript/UnityScript, so it'southward not too surprising it doesn't piece of work if y'all try to use it in a C# script. JavaScript also has neither the concept of Dictionaries, nor delegates, so the reverse is also true and your solution won't work in a JS script. Since the original question is in JS (which yous can recognize past looking at the variable type declaration, as well equally from the tag right next to the question championship), it's safe to presume OP wants a solution that works in JS.
- 1
- 2
- ›
Your respond
Welcome to Unity Answers
The best place to ask and answer questions about development with Unity.
To help users navigate the site nosotros take posted a site navigation guide.
If yous are a new user to Unity Answers, check out our FAQ for more data.
Make sure to check out our Knowledge Base of operations for commonly asked Unity questions.
If you lot are a moderator, run across our Moderator Guidelines page.
Nosotros are making improvements to UA, see the list of changes.

Follow this Question
Related Questions
Source: https://answers.unity.com/questions/165878/how-to-detect-which-key-is-pressed.html
Tin you elaborate to why you want to do it this way over using specific inputs. ie Input.getButton/cardinal etc
Well...Input.Become$$anonymous$$ey returns truthful or imitation, so I have to query each button separately. I would prefer a function that returns the pressed $$anonymous$$ey, so I can use a Switch() statement ins$$anonymous$$d of multiple if() statements. It looks nicer and also Switch() has a default that is used whenever a push is pressed that I did not specify.
surely if the condition of the switch is the bool result from a Input.get$$anonymous$$ey phone call then you lot can still use it that way without any extra ifs.
To mayhap make it clearer, here is the current version of the script. I have resorted to the multiple If statements and it does work, simply I accept encountered an error, that simply happens sporadically, so I would however exist thankful for a more elegant solution.
Information technology makes the player move a sure distance on a Hex Grid while at the same time activate the 'Plough' for the other GameObjects.
What is the error y'all are getting, but incase someone spots a solution to that (it cant hurt)?
Testify more comments