title: My script that uses a raycast to deal damage over time is causing Unity to crash. Anyone know why?
body: <p>I have created a script that makes an enemy deal damage over time to a player from a raycast but it is making Unity crash once I'm in the required range for the enemy to move and deal damage. Anyone know why?</p>
  
  <pre><code>using System.Collections;
   using System.Collections.Generic;
   using UnityEngine;
  
   public class EnemyMove : MonoBehaviour
   {
       public Transform target;
       public Transform player;
       public float enemySpeed;
       public int moveTrigger = 1;
       public bool isAttacking;
       public int AttackTirgger;
  
       public float distanceFromPlayer;
  
       void Update()
       {
           distanceFromPlayer = Vector3.Distance(target.transform.position, player.transform.position);
  
           if (distanceFromPlayer &lt;= 10 &amp;&amp; moveTrigger == 1)
           {
               transform.LookAt(target);
               if (!isAttacking)
                   StartCoroutine(EnemyDamage());
           }
           if (distanceFromPlayer &lt; 10 &amp;&amp; moveTrigger == 1 &amp;&amp; distanceFromPlayer &gt; 3)
           {
               transform.Translate(Vector3.forward * enemySpeed * Time.deltaTime);
           }
       }
  
       IEnumerator EnemyDamage()
       {
           isAttacking = true;
           while (distanceFromPlayer &lt;= 10)
           { // in range
               RaycastHit PlayerHit;
               if (Physics.Raycast(target.transform.position, target.transform.forward, out PlayerHit))
               {
                   Target target = PlayerHit.transform.GetComponent&lt;Target&gt;();
                   if (target != null)
                   {
                       GlobalHealth.playerHealth -= 1;
                       yield return new WaitForSeconds(2);
                   }
               }
           }
           isAttacking = false; // out of range
           yield return null;
       }
   }
  </code></pre>