Deal Damage Every Few Seconds

Hello, I’m making a game where the enemies are moving down the screen and once they reach the castle at the bottom of the screen, they do a certain amount of damage every few seconds. I did some research and tried placing an infinite loop inside a coroutine and used WaitForSeconds. This doesn’t seem to be working.It just waits 8 seconds and then deals damage constantly with no delay. I’ve added my code here. Thanks.

public class EnemyScript : MonoBehaviour
{
    [SerializeField] float enemySpeed;
    [SerializeField] Slider healthbar;

    void Update()
    {
        MoveEnemy();
        CheckCastle();

    }
    private void MoveEnemy()
    {
        if (transform.position.y > -3.24)
        {
            transform.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -enemySpeed);
        }
        else{
            transform.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
        }
    }
    public void CheckCastle()
    {
        if(transform.position.y < -3.24)
        {
            StartCoroutine(DamageCastle());
        }
    }

    IEnumerator DamageCastle(){
        while (true)
        {
            yield return new WaitForSeconds(8);
            healthbar.value -= 1;
        }
    }

}

woooow, on each update you start a new coroutine…

you on update call CheckCastle, to initialize a new coroutine DamageCastle

a simple solution to that is just set a global variable

 Coroutine watchDog;

and check if you initialize it just once on CheckCastle

 public void CheckCastle()
 {
     if(transform.position.y < -3.24)
     {
        if(watchDog == null)
             watchDog = StartCoroutine(DamageCastle());
     }
 }