If statements inside coroutine aren't running
Hey! Im making a health system for a game but for some reason when i try to use coroutines to delay the time between losing health it doesnt work at all. If i put the same if statement into an update function then it works perfectly but it instantly drains the health.
 public class BasicHealth : MonoBehaviour
 {
 
     static int maxHealth = 100;
     static int currentHealth = maxHealth;
     public GameObject healthGui;
     public GameObject Player;
 
 
     private void Start()
     {
         StartCoroutine("HealthLoss");
     }
 
     public IEnumerator HealthLoss()
     {
         if (GameObject.Find("Skeleton@Skin").GetComponent<FollowAndAttack>().isAttacking)
         {
             currentHealth = currentHealth - 10;
             Debug.Log(currentHealth);
             yield return new WaitForSeconds(1);
         }
 
     }
 
     private void Update()
     {
 
 
 
         if (currentHealth <= 0)
         {
 
             SceneManager.LoadScene("menu");
 
 
         }
 
 
     }
 
     private void OnGUI()
     {
         GUI.Label(new Rect(120, 25, 100, 20), currentHealth.ToString());
     }
 }
 
 
Answer by yummy81 · Jan 28, 2018 at 10:25 PM
You have to modify your coroutine this way:
 public IEnumerator HealthLoss()
 {
     while(true)
     {
         if (GameObject.Find("Skeleton@Skin").GetComponent<FollowAndAttack>().isAttacking)
         {
             currentHealth = currentHealth - 10;
             Debug.Log(currentHealth);
             yield return new WaitForSeconds(1);
         }
         yield return null;
     }
 }
A coroutine is not a de-facto loop.
That's why you need to add a while, or a for loop in it.
Answer by victorbisaev · Jan 28, 2018 at 10:15 PM
Try like this:
 public IEnumerator HealthLoss()
 {
     for (;;)
     {
         if (GameObject.Find("Skeleton@Skin").GetComponent<FollowAndAttack>().isAttacking)
         {
             currentHealth = currentHealth - 10;
             Debug.Log(currentHealth);
         }
 
         yield return new WaitForSeconds(1);
     }
 }
Your answer
 
 
             Follow this Question
Related Questions
How to interrupt wait coroutine in a loop? 0 Answers
nothing called after WaitForSeconds 1 Answer
Annoying Quaternions and Eulers 1 Answer
Start coroutines when the class is not a MonoBehaviour 1 Answer
C# waitForSeconds Question 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                