- Home /
Is there a more efficient alternative to execute code on a key press, except for checking if the key is pressed every frame?
Isn't there another way?
I feel like checking if the button is pressed in Update() isn't really efficient.
Actually i am an absolute beginner in Unity but shouldn't it be possible over the event system ?
Hello, key is press on Update have NO impact on performance, really easy to process! No need to worry. On the other side coroutine will allocate memory (GC), not a good choice
Answer by AurimasBlazulionis · Mar 05, 2017 at 04:47 PM
No, it really is not the reason why performance on your project is terrible. But what you could check out is this beta input system.
Answer by GregoryNeal · Mar 05, 2017 at 06:53 PM
If you just want to keep from cluttering your Update() method you could use a coroutine:
public IEnumerator DoActionOnKeyPress(Action a, KeyCode k) {
yield return new WaitUntil(()=>Input.GetKeyDown(k));
a();
yield break;
}
Just put this method in your script. To use it let's say you wanted to launch a ball from a paddle using the space key at the start of your game. Your script may look something like this:
using System;
using System.Collections;
using UnityEngine;
public class BallLaunch : MonoBehaviour {
void Start() {
/* set up the ball here */
StartCoroutine(DoActionOnKeyPress(LaunchBall, KeyCode.Space));
}
void LaunchBall() {
/* launch the ball from the paddle */
}
IEnumerator DoActionOnKeyPress(Action a, KeyCode k) {
yield return new WaitUntil(()=>Input.GetKeyDown(k));
a();
yield break;
}
}
You can replace LaunchBall
with any method name that has a void return type and takes no parameters. I use this method all the time. Enough in fact to warrant placing it in an extension script.
using System;
using System.Collections;
public static class ExtensionMethods {
public static IEnumerator DoActionOnKeyPress(this MonoBehaviour mb, Action a, KeyCode key) {
yield return new WaitUntil(()=>Input.GetKeyDown(key));
a();
yield break;
}
}
Then as long as you keep this script in your assets folder you can call StartCoroutine(this.DoActionOnKeyPress(_Action, KeyCode.Space));
in any of your monobehaviours.
i think the person asking is worried that he will miss some keystrokes, by querying the keyboard every 1/60 second.
Your answer
Follow this Question
Related Questions
2d player can get stuck in walls if you hold down (Not the physics material fixable glitch) 0 Answers
Variable goes very high in update method 1 Answer
Update function not picking up state changes 0 Answers
Why is GetKeyDown / Up behaving erratically, only responding occasionally in build? 1 Answer
Open door with key 2 Answers