- Home /
Detecting Pressed key and returning a KeyCode Variable
There are lots of answers on detecting which key was pressed but I need to get that as a KeyCode variable to reassign my controls and it is always returned as a string. I have a variable of KeyCode that i want to assign the next pressed key on the keyboard to move the character the direction. For example i have a variable KeyCode Foward1 = KeyCode.W; and when i press a button i have a public method called On Click() and i want it to detect the next key pressed and assign it to Foward1 but have no idea how to do this . Can I do it this way or do i need to use OnGUI()
Answer by Llourn · Sep 22, 2017 at 03:00 AM
Hi @Shananas . I did some looking around and found this. I hope it helps. :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public void DetectPressedKeyOrButton()
{
foreach(KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKeyDown(kcode))
Debug.Log("KeyCode down: " + kcode);
}
}
I think that would work if i replaced debug log with foward1 = kcode ill see if it works
Answer by xvivax · Sep 22, 2017 at 02:55 AM
Is it what are you looking for?
KeyCode tempKeyCode;
KeyCode Forward1;
void OnGUI()
{
Event e = Event.current;
if (e.isKey)
{
tempKeyCode = e.keyCode;
}
}
public void OnClick()
{
Forward1 = tempKeyCode;
}
That would only work if i created an if for every key so it seems inefficient but i might do that if i need to since it will do the job
It automatically detects any letter you press and pass it to temp$$anonymous$$eyCode. Don't be confused by e.$$anonymous$$eyCode it doesn't mean "e" letter, it is just an Event variable name.
Forgot that e was the event my bad. That unbinds the key the problem Im having now is my script is on the player and Im trying to use the buttons to change the script by assigning the newly hit key through the On Click function provided in unity once yo create a button so i wonder what is the best way to do this can i do it this way and change the script on my player or should i do another way
Your answer
Follow this Question
Related Questions
Multiple button name in a row? 1 Answer
Problem coding script for paddles in Pong without using any physics. 1 Answer
Check if pressed key exists inside an array of KeyCodes 2 Answers
How can make the player move constantly when the key A or D is held down? 1 Answer
animation does not work when one clone got destroy unity 1 Answer