- Home /
How can I get a combination of keys pressed?
Hello... I'm trying to get a combination of keys pressed or buttons held down.
The right thing is that I want to make a Ctrl+Z function in my proyect, so if I press the key Control, hold down it and then press the Z key, I want that my last action to be eliminated.
I have something like this, but it doesn't work at all...
Event e = Event.current; if (e.control) { print("control!"); if (Input.GetKeyDown("Z")) { print("Deshacer!"); }
if (Input.GetKeyDown("Y")) { print("Rehacer!"); } }
You could be a bit more precisely. Where do you use this code? In Update or in OnGUI? What get printed? nothing? As i said in my answer, Event is only for GUI events and is only available in OnGUI
Answer by Bunny83 · Feb 24, 2011 at 05:47 PM
The Event class should only be used in OnGUI() and the Input class should not be used in OnGUI.
For combination like CTRL-Z you can use:
void OnGUI()
{
Event e = Event.current;
if (e.type == EventType.KeyDown && e.control && e.keyCode == KeyCode.Z)
{
// CTRL + Z
}
}
or what should also work:
void Update()
{
if ((Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftControl)) && Input.GetKeyDown(KeyCode.Z))
{
// CTRL + Z
}
}
@Alejandro: Be warned that while testing in the editor, Ctrl Z may not appear to function properly; in my tests Unity actually thought I was trying to undo something and it never registered in the game.
However, when I built the game, the same script worked fine.
Sure, that's one of those combinations that won't work in the editor properly. ;)
@paulius-liekis: Not really. It is a built-in combination of the editor itself, like CTRL+ALT+$$anonymous$$ is built-in the OS. You either use a different combination or use it only in your final build.
I beleive something like this would work as a work around/$$anonymous$$ake it so you don't have to remember to change it on final build:
#if UNITY_EDITOR
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.Z))
#else
if((Input.Get$$anonymous$$ey($$anonymous$$eyCode.RightControl) || Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftControl)) && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Z))
#endif
{
UndoLastAction();
}
Answer by martin-3dar · Dec 11, 2016 at 10:53 PM
this might be useful for anyone running this question:
https://docs.unity3d.com/ScriptReference/Input-inputString.html
Answer by vladipetrenko · Nov 18, 2018 at 02:11 PM
On Unity 2018.2.7f1 for Linux, please use this:
Event e = Event.current;
if (e.type == EventType.KeyUp && e.control && e.keyCode == KeyCode.S)
{
Debug.Log("SAVE");
}
I don't get this answer. You use a different key combination and use the keyup event. What's the reason for that? Note that CTRL + Z obviously doesn't work properly inside the editor but does work inside a build (as discussed above). Without giving a proper reason for your suggested change this answer seems pretty pointless.