-1
\$\begingroup\$

None of the code after wait for seconds runs in the example below.

The idea is to stop the player attacking for 1 second after he hits an enemy.

When I run this code, Debug.Log "start coroutine" appears in the console, but "endcoroutine" doesn't, and CanHit doesn't return to true.

How can I fix this so the coroutine resumes after the wait?

public class Attack : MonoBehaviour

{

private bool CanHit = true;

   private void OnTriggerEnter2D(Collider2D other)
    {
        IDamageable Hit = other.GetComponent<IDamageable>();

        if (Hit != null && CanHit == true)
        {
            Hit.Damage();
            StartCoroutine(ResetDamage());
        }
    }

    IEnumerator ResetDamage()
    {
        CanHit = false;
        Debug.Log("start coroutine");
        yield return new WaitForSeconds(1.0f);
        Debug.Log("end coroutine");
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Well you don't have CanHit = true; anywhere in the code you have provided. \$\endgroup\$ Jul 24 '19 at 15:03
  • \$\begingroup\$ Does something destroy or deactivate the game object this coroutine is running on in the second while it's waiting? Coroutine lifetime is tied to the instance that started it, so this can kill the coroutine before it has a chance to resume. \$\endgroup\$
    – DMGregory
    Jul 24 '19 at 16:08
  • \$\begingroup\$ Ye I deactivated the instance in the last few frames of the animation!!! All sorted now thanx @DMGregory \$\endgroup\$
    – Haz3rd
    Jul 24 '19 at 18:40
0
\$\begingroup\$

nothing to do with the code0. I had disabled the object the code was attached to in the last few frames of my animation, that's what was causing the issue.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.