using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
void Start ()
{
StartCoroutine (“Grab”);
}
IEnumerator Grab ()
{
if (Input.GetKey(“t”))
{
print(“t”);
yield return new WaitForSeconds(1f);
print(“1”);
}
}
}
I was wondering why this does not work, and if there is a way to make it work.
Also, can someone please explain why it does not work (and maybe just a bit about coroutines). I am really new to this so please don’t use big words that would be really confusing. Thanks!!
Coroutines pretty much behave like any other function or method that you create, except the fact that you can halt execution of that coroutine with a YieldInstruction. This can be various things from seconds, to return input that send back to it to continue execution of the code inside the coroutine. It’s similar to creating threads in the generic .NET environment, if you want to read some about that as well.
So, with that said, I’m going to assume that you want the Grab() IEnumerator to constantly check for the GetKey “t”. If that is the case, then if you take a look at your coroutine and think about it, it’s simply going to execute once after it’s started from your Start() method, and if it isn’t pressed, the coroutine will end it’s execution loop and won’t be checking anymore.
You’ll have to put your if statement inside some kind of loop, such as a while loop, and use a conditional to keep it running. So take for example, if your script is attached to a Game Object and is active, you could do something like.
IEnumerator Grab()
{
while( gameObject.active )
{
if( Input.GetKey("t") )
{
print("t");
yield return new WaitForSeconds(1);
print("1");
}
yield return null;
}
}
You have to also add the yield return null ( or other value ) in there because coroutines expect a YieldInstruction as a return in order to continue processing. Since you simply just want to keep the while loop running, I just return a null value. You could also just yield if you wanted to wait for execution of the next frame, and so on.
It is not so efficient to check input controls in a Coroutine.You call Grab() function in Start and it calls it just one time when script is able to execute. You can not catch Input.GetKey function in that coroutine because it is being executed really fast.But as dannyskim said, you can check it in a loop or smt but my suggestion is don’t do in a coroutine, do it in update function and if key is pressed then start coroutine.