How to delay an action in Untiy
Lets say, that you have a action:
void doSomething() {
//it does something
}
And you want to execute this action when a key is pressed:
void Update() {
if (Input.GetKey(KeyCode.someKey) {
doSomething();
}
}
BUT: you don't want to execute this action EVERY SINGLE FRAME THE USER PRESSES THE KEY.
For instance, if you have a semi-automatic rifle, and you hold down a key, you want to fire every second or two seconds.
HOW?
I will appreciate any help ASAP.
BTW: This doesn't work:
IEnumeratior bla() {
doSomething();
yield return new WaitForSeconds(1);
}
void Update() {
if (...) {
StartCoroutine("bla");
}
}
Answer by flashframe · Feb 21, 2016 at 07:47 PM
Your coroutine would work if you were using GetKeyDown instead of GetKey. (Although there's a typo in the coroutine you posted here; it should be "IEnumerator")
Use GetKeyDown to start firing and GetKeyUp to stop firing.
void Update()
{
if(Input.GetKeyDown(KeyCode.someKey)
{
StartCoroutine("bla");
}
if(Input.GetKeyUp(KeyCode.someKey)
{
StopCoroutine("bla");
}
}
You could also use InvokeRepeating() and CancelInvoke() instead of a coroutine, which might be better in this case.
http://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html http://docs.unity3d.com/ScriptReference/MonoBehaviour.CancelInvoke.html