- Home /
Event Trigger For Key Pressed
Is there anyway to get an event trigger to handle when a Key's pressed? I looked through what you could assign the event trigger and I wasn't able to find anything like that.
Answer by ExamplesAreExamples · Nov 25, 2015 at 02:22 PM
Unity does not send Key events using the new Event System.
For reference, here's a list of all supported events.
However, you can still process input events if you are the selected object. They are just not sent through the Event System.
See the implementation of InputField.OnUpdateSelected, for reference. This is how Unitys UI uses keyboard input. You'll notice it's very similar to how the old IMGUI got key events from Event.current
. Instead, here they use Event.PopEvent
in a while loop instead of calling OnGUI several times per frame.
Answer by btft · Nov 25, 2015 at 03:16 PM
I'm afraid you need to create simple script and catch the key on Update:
public void Update()
{
if (Input.GetKeyUp(KeyCode.X))
{
//do stuff
}
}
Does this make it so when you press x it does stuff
Answer by ___... · Nov 25, 2015 at 12:02 PM
Input has to be checked every frame in Update. There are different functions available. Some just return the state of a button (down or up) some will return true only the frame a button has been pressed down or up. Buttons have to be defined in the input manager.
There are also functions for reading certain keyboard-keys
Input.GetKey
Input.GetKeyDown
Input.GetKeyUp
In general just look into the scripting reference
A script that toggles a light could look like this:
// UnityScript (Unity's Javascript)
function Update()
{
if (Input.GetMouseButtonDown(0)) // 0 - left button; 1 - right button; 2 - middle button
{
light.enabled = !light.enabled;
}
}
Make sure you attach this script to a GameObject that has a Light component attached ;)
The same script in C#:
// C#
// FlashLightControl.cs
using UnityEngine;
public class FlashLightControl : MonoBehaviour
[
void Update()
{
if (Input.GetMouseButtonDown(0))
{
light.enabled = !light.enabled;
}
}
}
Answer by BenBB · Nov 25, 2015 at 12:02 PM
You can write a script that manages the keys like this (js) :
var key : KeyCode;
function Update () {
if(Input.GetKey(key)) {
//here you put the code of your event
}
}