My player is able to dive for a limited amount of seconds (let's say 10 seconds) while swimming. When he's not diving his breath gauge fills up again to a max of 10 seconds:
private bool isFreediving; private float breath = 10f; void Update() { if (isFreediving) { if (breath > 0) { breath -= Time.deltaTime; Debug.Log(breath); } else { Debug.Log("Out of breath"); breath = 0; // optional? isFreediving = false; // Do staff... } } else { if (breath == 0) { // TODO: Make the player stop moving for 1 second // TODO: Stop breath += Time.deltaTime for 3 seconds } else if (breath > 0 && breath < 10) { breath += Time.deltaTime; // TODO: Make breath fill up slower/faster Debug.Log(breath); } } } If the player runs out of breath completely, I want him to stop moving for a second and I also want the breath gauge to not start to fill up for 3 seconds. I tried with coroutines, but my code is inside the Update() method, so it didn't work. I realize that the above If-else statements need to be rearranged properly.
Lastly, I want the breath gauge to be filled up at a different pace, for example:
breath += Time.deltaTime * 0.5f; I wonder if there is a better way?
EDIT: After @Pow's solution:
float swimSpeed = 0.03f; private bool isFreediving; private float breath = 10f; private bool canRefillBreath; void Update() { float swimAmount = Input.GetAxis("Vertical") * swimSpeed; transform.Translate(0, swimAmount, 0); if (isFreediving) { if (breath > 0) breath -= Time.deltaTime; else { breath = 0; isFreediving = false; // Do staff... canRefillBreath = false; } } else { if (breath == 0) { swimSpeed = 0; Invoke(nameof(EnableSwim), 1f); Invoke(nameof(EnableRefill), 3f); } if (canRefillBreath && breath < 10) breath += Time.deltaTime; } } private void EnableSwim() => swimSpeed = 0.03f; private void EnableRefill() => canRefillBreath = true; The only weird thing is that after 1 second the player starts moving at a slower rate until the 3 seconds Invoke(nameof(EnableRefill), 3f);, then he goes full speed.
Invoke(nameof(EnableSwim), 1f);\$\endgroup\$EnableRefillrun out.EnableSwimandEnableRefillshouldn't affect each other, but they do. Perhaps the contemporarity slows the cpu, although the two Invokes don't consume much memory. \$\endgroup\$