- Home /
Time.deltaTime not working with while loop
So I'm making a little fighting game for the first time and I need to check if something is overlapping with my character's hurtbox. So I made this while loop with Time.deltaTime to keep checking if it's registered a hit within the time frame given. However, as soon as it's called it just counts the timer down from 100% to 0% instantly.
private void LaunchAttack(float damage,string animatorString, Collider2D collider)
{
bool breaker = true;
float curAttackTiming = attackTiming;
canAttack = false;
curDamage = damage;
myAnimator.SetBool(animatorString, true);
while (curAttackTiming > 0)
{
Debug.Log(curAttackTiming);
curAttackTiming -= Time.deltaTime;
var enemyCol = Physics2D.OverlapBox(collider.bounds.center, collider.bounds.extents * 2, 0, LayerMask.GetMask("EnemyHitbox"));
if (enemyCol & breaker)
{
Debug.Log("LaunchAttack enemyCol & breaker");
enemyCol.GetComponentInParent<Health>().SubtractHealth(curDamage);
breaker = false;
curDamage = 0;
}
}
}
As soon as I start the attack it gives me all this instantly: https://cdn.discordapp.com/attachments/496103505317330944/630928579655368704/unknown.png
How would I be able to make a proper timer? I just need to be able to keep checking for overlaps only when specified. I hope that made sense and thanks in advance.
Answer by revolute · Oct 08, 2019 at 02:29 AM
Unity updates Time.deltaTime before it enters a phase. Essentially, each "Update", "FixedUpdate" and others are grouped into collective groups and before Unity internally runs each of the groups, Time.deltaTime is updated. This means that during the same phase, deltaTime remains same. Calling Time.deltaTime in the same frame in the same group will result in same value. You need to "let go" of current loop and wait for next update.
The "let go" practically means you need to yield, and in this case I recommend using coroutines.
But then I wouldn't be able to keep checking if something is overlapping the hurtbox right? Wouldn't the coroutine just check it once before or after the yield? I need to be able to check if something is overlapping during the animation in case something enters the hurtbox slightly after the attack is initiated that way the player doesn't feel cheated in niche circumstances.
Yes you can check it. while(true) yield return null; would allow you do check every frame as long as the coroutine is alive.
Depending on which function and how animation updates are handled, you either know the overlap happens on the exact frame or in the next frame. That behavior is hard to define since I have no knowledge which update you are using for animations.
Your answer
Follow this Question
Related Questions
Decrease a value every second? 3 Answers
What is wrong in my code - Unity freezes 1 Answer
start coroutine everytime 2 Answers
Moving out of collision with trigger using while loop crashes Unity. 1 Answer