Home > Back-end >  How can I determine a pressed button in certain time window and do one action?
How can I determine a pressed button in certain time window and do one action?

Time:10-20

I have an enemy which does an attack. If the player hasn't pressed a button to defend himself at that moment, he will receive damage for this attack. So far I'm checking in Update if any attack animation is playing and start a Coroutine.

{
    if ( enemy.CheckIfAnimationIsPlaying ( "Enemy_mainAttack" ) || 
        enemy.CheckIfAnimationIsPlaying ( "Enemy_mainAttack2" ) || 
        enemy.CheckIfAnimationIsPlaying ( "Enemy_firstAttack" ) )
    {
        StartCoroutine ( DefendTiming ( ) );
    }
}

private IEnumerator DefendTiming ( )
{
    float animationLength = enemy.animator.GetCurrentAnimatorStateInfo(0).length;
    yield return new WaitForSeconds ( animationLength );

    if ( !defendButtonPressed && !receivedDamage )
    {
        ReceiveDamage ( enemy.attack );
        receivedDamage = true;
    }
    else
    {
        this.ReduceEndurance ( false, 3 );
        defendButtonPressed = true;
    }
}

But this approach doesn't work properly and looks not suitable. Thanks for help :)

CodePudding user response:

Add EventTrigger component to your button and use its functions like PointerDown and PointerUp for setting your bool(s).

EventTrigger Component

CodePudding user response:

You can store the started coroutine in a Coroutine and stop it when the button is pressed. Something like that:

private Coroutine _defTimingCoroutine;

private void OnEnemyAttack()
{
    ...
    _defTimingCoroutine = StartCoroutine(DefendTiming);
}

private void OnButtonClick()
{
    StopCoroutine(DefendTiming);
    // other things like stop animation, etc.
}
  • Related