- Home /
Is there a more efficient way to make events for keyboard key presses?
I'm trying to use events to handle keyboard key presses instead of calling a function each time a key is pressed, to make the game easier to work with.
The issue I'm having is that creating the event for a single key is quite long, and will have to be looped every frame in Update(). This seems inefficient, after a while you are looping through a couple hundred checks per frame. I read up on EventType.KeyDown, EventType.KeyUp,and Event.current , but was unable to figure out how to use those instead of making my own events.
Thoughts?
public delegate void UpButtonHandler();
public static event UpButtonHandler UpButtonHeld;
public static event UpButtonHandler UpButtonUp;
private static void UpButton(){
if (Input.GetButton("KeyUp")){
if (UpButtonHeldEvent != null)
UpButtonHeldEvent();
}
}
private static void UpButtonUp(){
if (Input.GetButtonUp("KeyUp")){
Debug.Log("working?");
if (UpButtonUpEvent != null)
UpButtonUpEvent();
}
}
Edit:
Just discovered:
public void test(){
if (Event.current.keyCode == KeyCode.W){
Debug.Log("Event works");
}
}
This seems to work, but it has to be ran in OnGUI(){}. Is there any disadvantage to running something like this in OnGUI vs Update() ? I also can't think of a way to add subscribers to such an event.
Day 1 Edit: Started using the first example in my application, though am still very much interested in the 2nd Event.current and how I might be able to make a subscriber to that event, as well as the performance of the first way.
Day2: Still was unable to find out much more than this. The events work well (amazingly well) though. Edited example a bit.
Day5: Not finding out much more :/
I don't really see the point of rewriting something that is working. On top of that, you will hardly get the same performance UnityEngine is providing since input is probably run on the C++ side.
Finally, ever since 4.6 OnGUI is dead to me. There is a reason why they call it legacy GUI and why some companies spent so long to develop better version (NGUI for instance).
Just leave OnGUI in the drawer and just take it out to re$$anonymous$$d you how harder the old days were.
What do you guys mean?
If there is a way to subscribe to the unity input events, how do I do that? Otherwise I have to poll for them and publish my own events in the way mentioned above.
Your answer
Follow this Question
Related Questions
C# Delegates, a question 1 Answer
Why doesn't unregistering an anonymous delegate trigger an error? 1 Answer
Sharing delegate types across scripts 1 Answer
Destroy(gameObject) only works once 1 Answer
Create delegate from MethodInfo 1 Answer