What I need is to increment player stats every few second and be able to interrupt this process with any key pressed down.
Below is my coroutine. It's running endlessly, any advice?
IEnumerator PlayerAction(PlayerStats playerStats, int incrementor1)
{
bool loop = true;
while (loop)
{
if (Input.anyKeyDown)
{
loop = false;
Debug.Log("Action is break");
yield break;
}
else
{
yield return new WaitForSeconds(2);
playerStats.Energy += incrementor1;
GameClock.Tic++;
Debug.Log("My first courutine is working!");
}
}
}
Yes. Don't use
yield return new WaitForSeconds
to wait. You will miss the Input event (if (Input.anyKeyDown)
) during this frame.Another way to make counter in a coroutine function is to use
Time.deltaTime;
to increment a variable, then wait withyield return null;
which only waits for a frame instead of seconds, when you useyield return new WaitForSeconds
.This is what I explained above should look like:
Make sure to call a coroutine with the
StartCoroutine
function likeStartCoroutine(PlayerAction(yourPlayerStat,2));