title: Display and count killed enemies in Unity3D C#
body: <p>I'm new to Unity3D and I am trying to count all the enemies I have killed on runtime and display in <code>OnGUI()</code>. What I did was that for every time the enemy is killed, I am going to increment: <code>enemyKilled</code>. However, when it does... some time in the program... the display decrements and then disappears.</p>
  
  <pre><code>public class ShootableBox : MonoBehaviour {
  
      Animator anim;
      public int currentHealth = 3;       
      public int enemyKilled;         // Count how many enemies you have killed           
      public float currentHealthLength;
  
      bool isSinking;                     // To trigger the dead enemy to sink
      public float sinkSpeed = 1f;        // Sink speed
  
      void Start() {
          anim = GetComponent&lt;Animator&gt;();
          currentHealthLength = Screen.width/2;
          enemyKilled = 0;
      }
  
      void Update ()
      {   
          // If the enemy should be sinking...
          if(isSinking)
          {
              transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
          }       
      }
  
  
      public void Damage(int damageAmount)
      {
          //subtract damage amount when Damage function is called
          currentHealth -= damageAmount;
  
          //Check if health has fallen below zero
          if (currentHealth &lt;= 0) {
              enemyKilled = enemyKilled + 1;
              //if health has fallen below zero, deactivate it 
              anim.SetTrigger ("isDead");
              //transform.GetComponent&lt;NavMeshAgent&gt; ().Stop ();
  
              // Find and disable the Nav Mesh Agent.
              GetComponent &lt;NavMeshAgent&gt; ().enabled = false;
  
              // Find the rigidbody component and make it kinematic (since we use Translate to sink the enemy).
              GetComponent &lt;Rigidbody&gt; ().isKinematic = true;
  
              Invoke ("StartSinking", 2.5f);
  
          } else {
              anim.SetTrigger("isHit");
              anim.SetTrigger("isRun2");
          }
      }
  
      public void StartSinking() {
  
          // The enemy should now sink.
          isSinking = true;
          // After 2 seconds destory the enemy.
          Destroy (gameObject, 8f);
      }
  
      // My problem is somewhere on this part
      public void OnGUI() {
  
          GUI.contentColor = Color.yellow;
  
          if (enemyKilled != 0) {
  
              GUI.Box(new Rect(5, 5, currentHealthLength, 20), "Enemies killed: " + enemyKilled );
          }
      }
  }
  </code></pre>
  
  <p>I can already kill the enemy on runtime. I just can't seem to display the correct number of enemies dead right. How can I fix this error? Thank you so much for all of your help.</p>