Search Unity

Resolved UI Text ist not Update but in Inspector Fixing if you use Firebase!

Discussion in 'UGUI & TextMesh Pro' started by ShadowlessStudios, Nov 16, 2022.

  1. ShadowlessStudios

    ShadowlessStudios

    Joined:
    Jan 8, 2017
    Posts:
    16
    I've had this problem for years but never really tried to fix it until yesterday. It took me almost 1 day with no solution. I've done so many workarounds to solve it in some way without fixing it.

    But finally the solution! :

    The problem is that the tasks you run are run in a separate thread. This is how asynchronous tasks work, especially with Firebase. You must first connect it to the main thread using the extension method

    Code (csharp):
    1. ContinueWithOnMainThread
    instead of
    Code (csharp):
    1. ContinueWith
    .


    That's it!!

    More info: https://firebase.google.com/docs/re...-extension#continuewithonmainthread-tresult_1

    This appears when you try to set the UI asynchronously, which doesn't work because Unity runs everything on the main thread. Hope this helps someone else :)

    :)

    An Example of my Code befor and after:

    Befor:

    Code (CSharp):
    1.     public void GetOnlineUsersCount()   //To get data from FireBase
    2.   {
    3.     databaseReferenceOnlinePlayers.GetValueAsync().ContinueWith(task =>
    4.     {
    5.       int totalChild = (int)task.Result.ChildrenCount;
    6.       FireBaseData.OnlinePlayers = totalChild;
    7.     });
    8.     //StartCoroutine(GetOnlinePlayers((int data) => { GameData.OnlinePlayers = data; }));
    9.   }


    After:
    Code (CSharp):
    1.     public void GetOnlineUsersCount()   //To get data from FireBase
    2.   {
    3.     databaseReferenceOnlinePlayers.GetValueAsync().ContinueWithOnMainThread(task =>
    4.     {
    5.       int totalChild = (int)task.Result.ChildrenCount;
    6.       FireBaseData.OnlinePlayers = totalChild;
    7.     });
    8.     //StartCoroutine(GetOnlinePlayers((int data) => { GameData.OnlinePlayers = data; }));
    9.   }