Search Unity

Coroutine not continuing after yeild return new waitforsconds time

Discussion in 'Scripting' started by ToastHatter, Sep 16, 2017.

  1. ToastHatter

    ToastHatter

    Joined:
    Nov 11, 2016
    Posts:
    53
    For some reason when i run a coroutine in a specific script it doesn't continue after the yeild new waitforseconds.

    It sometimes does but most of the time it doesn't, can any one try to point out where the error maybe.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6. public class WeakSpot : MonoBehaviour {
    7.  
    8.     public Boss Boss;
    9.  
    10.     public float Damage;
    11.  
    12.     public GameObject self;
    13.     public Collider2D Hitbox;
    14.  
    15.  
    16.     void OnTriggerEnter2D(Collider2D other)
    17.     {
    18.         if (other.gameObject.CompareTag ("Player")) {
    19.             Boss.life = Boss.life - Damage;
    20.  
    21.             StartCoroutine ("Respawn");
    22.  
    23.         }
    24.     }
    25.  
    26.     IEnumerator Respawn (){
    27.         print("ienumerator started");
    28.         self.gameObject.SetActive (false);
    29.         Hitbox.enabled = false;
    30.  
    31.         print("bools done");
    32.  
    33.         yield return new WaitForSeconds (0.5f);
    34.  
    35.         print("Yield started");
    36.         self.gameObject.SetActive (true);
    37.         Hitbox.enabled = true;
    38.         print("Yield eneded");
    39.  
    40.     }
    41. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    All Monobehaviors on inactive GameObjects will not have their coroutines resume following a yield, until the GameObject is once again active.

    It appears you might be .SetActive(false)-ing the object at the start of your coroutine, which means the coroutine dies with it at the yield, unless something else makes the object active again.

    That is... if I'm reading "self" correctly. But "self" could be a completely different GameObject, I don't know how you set stuff up.

    (edited to reflect error pointed out by @Suddoha ... thanks man!)
     
    Last edited: Sep 16, 2017
  3. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    You deactive the object (i assume 'self' is exactly the object you attach this script to), this inheritenly stops all coroutines associated with it.
     
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    This does not cancel a coroutine, at least not in the latests versions.
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    You are correct sir. I am amending my post. Good catch.