Search Unity

How to reach StartCoroutine() with non active game object?

Discussion in 'Scripting' started by huseyinbaba58, Aug 3, 2020.

  1. huseyinbaba58

    huseyinbaba58

    Joined:
    Feb 12, 2020
    Posts:
    146
    Code (CSharp):
    1. public class Saglik : MonoBehaviour
    2. {
    3.     public float can = 100f; //Can değişkeni
    4.     public Vector3 konum;
    5.    void Update()
    6.     {
    7.         konum = transform.position;
    8.     }
    9.    public void canKaybi(float hasar)
    10.     {
    11.         can -= hasar;
    12.         if (can <= 0f)
    13.         {
    14.            
    15.             StartCoroutine(Dirilme(this.gameObject));
    16.            
    17.              
    18.         }
    19.      
    20.     }
    21.     IEnumerator Dirilme(GameObject oyunNesnesi)
    22.     {
    23.         gameObject.SetActive(false);
    24.         yield return new WaitForSeconds(2);
    25.         oyunNesnesi.transform.position = new Vector3(1f, 0f, 0f);
    26.         oyunNesnesi.SetActive(true); //Oyun nesnesi devrede.
    27.         can = 100f; //Can yeniden 100f e yükseltildi.
    28.     }
    29. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Coroutines will not run on deactivated objects. After line 23, the coroutine will simply not continue. The workaround is to simply run the coroutine on a different GameObject, which will not be deactivated.
     
  3. huseyinbaba58

    huseyinbaba58

    Joined:
    Feb 12, 2020
    Posts:
    146
    Thank you so much.I will fix my mistake.