Coroutine vs Async Unity C#

Поделиться
HTML-код
  • Опубликовано: 26 окт 2024

Комментарии • 4

  • @bxb5625
    @bxb5625 5 дней назад +1

    great video but you're kinda wrong, the exemple you show isn't a use case where you would prefere async over coroutine. You mention that async work best for this since they give us access to invalidation Token but Coroutine do too, it's the coroutine it self. When you call StartCoroutine on your monobehaviour, this will return an Object of type coroutine which you can store just like your token. You can know call StopCoroutine passing this Coroutine and this will stop the coroutine for you. Just be sure to set your coroutine variable to null once you are done with it.
    Ex:
    IEnumerator MyEnumerator(){
    yield new WaitForSeconds( 10 );
    MyCoroutine = null;
    }
    MyCoroutine = StartCoroutine( MyEnumerator() );
    now you can if you want at some point do
    if ( MyCoroutine != null ){
    StopCoroutine( MyCoroutine );
    MyCoroutine = null
    //Handle what to do if their is a coroutine already running
    }
    // The rest of your logic normally

    • @bxb5625
      @bxb5625 5 дней назад

      + Another point to reconsider your need of an async function, coroutine are single threaded and run on the main thread but async don't, this means that some unity fonctionnality are straight up not accessible from async. Or At least until Unity 6, I didn't try this with the new Awaitable unity introduce

    • @TechHamlin
      @TechHamlin  5 дней назад +1

      Thanks for sharing that! Oh I thought not being in the main thread always would be a good thing. What kind of functionality did you miss at least before unity 6? I never thought about that scenario

    • @TechHamlin
      @TechHamlin  5 дней назад

      Thank you so much for clarifying that