I am not very good with coroutines and am trying to make something in my game. My goal is to make it so if the player stays still for a certain amount of seconds (in this case, 3), it will call a function. I am trying to use coroutines, but I have not been able to make them work. Here is my code so far:
...
public float waitTime;
void Update()
{
if (Input.GetKey(KeyCode.E) && rb.velocity.x <= stillVelocity.x && rb.velocity.y <= stillVelocity.y)
{
StartCoroutine(coroutine());
}
else
{
StopCoroutine(coroutine());
}
}
IEnumerator coroutine()
{
yield return new WaitForSeconds(waitTime);
method();
}
void method()
{
Debug.Log("It all worked");
}
I did manage to get the "It all worked" in my log, but not the way I intended it. It would print it even if I had let go of E before the waitTime had passed. The velocity checking works fine.
Now, I should probably say what I wanted the script to do. I wanted the script to detect if the player is still and they are holding the E key down for waitTime seconds. How this will apply to an actual game is this: I am making a system where the player can raise a checkpoint. This checkpoint is the spawnpoint from then on until a new checkpoint is created. I can do the checkpoint/spawnpoint thing on my own, and only need help with coroutines.
I may be wrong with the idea of using coroutines. I chose to use them in this case because I heard that I should use them when my code works with time. I also think I need to practice using them more to get a better understanding of them.
Here are my questions:
- Am I right in use coroutines here?
- If so, how would I use the coroutines?
- If not, when should I use them?
(Please use coroutines in your answer unless it is absolutely impossible to do it without them. I would prefer this, because I can do it without the coroutines, but, as said above, I need the practice.)