Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Problem with WaitForSecond

Discussion in 'Scripting' started by nanovasco, Mar 11, 2016.

  1. nanovasco

    nanovasco

    Joined:
    Oct 17, 2015
    Posts:
    1
    I'm doing a simple app, where my objects appear in certain time. I'm following some recommendations of other forums about the subject, but with this script my object dissappear but never appear again. What is wrong with my code?

    using UnityEngine;
    using System.Collections;

    public class aparece : MonoBehaviour {


    public float tiempo;



    // Use this for initialization
    void Start() {

    StartCoroutine(Espera());

    }

    IEnumerator Espera() {

    gameObject.SetActive (false);

    yield return new WaitForSeconds(tiempo);

    gameObject.SetActive (true);
    }
    // Update is called once per frame
    void Update () {

    }
    }
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Using code tags when posting code to the forums in the future will make it easier for others to help you.

    I don't see anything wrong, but if your timescale is set to 0, WaitForSeconds will never finish. If your GameObject with this component attached is disabled or destroyed, the coroutine will not continue.
     
  3. Zaflis

    Zaflis

    Joined:
    May 26, 2014
    Posts:
    438
    So he should instead disable just renderer or put all visual objects in a sub-object and then disable that?
     
  4. eppz

    eppz

    Joined:
    Aug 2, 2014
    Posts:
    172
    My guess too. Runtime won't enter the coroutine anymore after the object gone inactive.

    But you really should use Invoke (with delay), or simply create / play automatically an animation doing the same show/hide behaviour (without any piece of code).
     
  5. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    The coroutine does start, but the object is set to inactive inside the routine, so the coroutine never updates.

    Either will work, I recommend a sub-object.

    You can also call StartCoroutine() from another object, then THAT object will update the routine instead of the original. So from some other class, if you call StartCoroutine(apareceObject.Espera()), you can disable your apareceObject and the coroutine will still continue. For this, the Espera function will need to be public.