Search Unity

System.Threading.Tasks and GameObject.SetActive(true/false)

Discussion in 'Editor & General Support' started by Kragh, Sep 4, 2019.

  1. Kragh

    Kragh

    Joined:
    Jan 22, 2008
    Posts:
    657
    Hi there
    Can somebody please confirm that specific actions in Unity fails silently when invoked inside a async Task chain? I have several setups in my latest project (Firebase, realtime Database based), that are very dependent on Tasks and ContinueWith setups, but whenever I then try and do certain Unity actions in these function (Or callbacks from them), nothing happens. So far I have two main things that just fails without error or anything: Everything to do with PlayerPrefs, and SetActive on GameObjects.
    Not only do these functions fail silently, but everything after a given line with such a call, will simply not be done. I can debug fine in a Task. Just not call certain built-in functions in Unity.
    Right now the only way I have found to make this work, is to start a Coroutine as a response to a Task succes, and then let this function do the next step, when it notice a certain state being true. Something like:

    1) Just before a Task is begun, start a coroutine which will test for some state.
    2) Start Task (And Whatever continueWiths it has)
    3) At "Success" (Or failure), set certain value, so that coroutine will end in a new callback (Based on Tasks result) to whatever function I need, that has some of these forbidden calls in them (SetActive, PlayerPrefs.SetInt/string especially).

    But it sucks. And by now my code is messy because of this approach, even though I have designed a rather nice environment around this hack, to ease this workflow. Anything? Ideas? Other approaches? Can somebody explain WHY this happens?
    This is only tested in editor, may work fine on devices.
     
    AnastasiiaIT likes this.
  2. AnastasiiaIT

    AnastasiiaIT

    Joined:
    Dec 14, 2020
    Posts:
    3
    Hi, Kragh.
    I am dealing with the same problem now. I have Firebase (realtime Database, Storage and Auth) in my project. When I call myGameObj.setActive() or even myText.text = dataFromDB inside dbRef.GetValueAsync().ContinueWith(...) it does nothing as you described.
    Must say everything was fine until I added FirebaseAuth... Can you please answer me, did you find the reason why this problem appeared?
     
  3. AnastasiiaIT

    AnastasiiaIT

    Joined:
    Dec 14, 2020
    Posts:
    3
    FOR EVERYONE WHO FACES THE SAME PROBLEM!

    SOLUTION IS:
    1. Add "using Firebase.Extentions;"
    2. Replase alll "continueWith" with "ContinueWithOnMainThread"

    READY. Now everything works in main thread, as Unity likes!