Start coroutine on an inactive/de-activated GameObject

前端 未结 2 577
余生分开走
余生分开走 2020-12-12 02:47

I have the following code:

void Start()
{
    gameObject.SetActive(false);
    StartCoroutine(Load());
}

IEnumerator Load()
{
    yield return new WaitForSe         


        
2条回答
  •  再見小時候
    2020-12-12 03:43

    What I do to avoid stopping coroutine is have a game object that does not get deactivated.

    public class CoroutineHandler : MonoBehaviour
    {
        private static CoroutineHandler instance = null;
        public static CoroutineHandler Instance
        {
            get
            {
                if(instance == null)
                {
                    GameObject inst = new GameObject("CoroutineHandler");
                    DontDestroyOnLoad(inst);
                    instance = inst.AddComponent();
                }
                return instance;
            }
        }
    }
    

    Then use this for such coroutines by using CoroutineHandler.Instance.StartCoroutine(RoutineMethodHere());.

    If you do not want something like this, since it can go wrong or cause leaks if not handled correctly, you can try using Invoke("MethodName", delay);

提交回复
热议问题