簡體   English   中英

UnityEngine.UI.Text 沒有在異步方法中更新

[英]UnityEngine.UI.Text is not updating inside async method

我有一個腳本 MenuManager.cs amd 我這個腳本我在 firebase 火石中獲得了兩個文檔,這很好用,但是當我將結果設置為文本時,不工作

using Firebase.Firestore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Json;
using UnityEngine;

public class MenuManager : MonoBehaviour
{
    private Usuario usuario;
    private Rank rank;
    private CollectionReference usuarioCollection;
    private CollectionReference rankCollection;

    public GameObject rankNomeLabel;

    public bool infoCarregadas;

    public GameObject botaoInfo;
    
    void Start()
    {
        this.rank = new Rank();
        this.botaoInfo.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => this.CarregaInfos());
        //this.infoCarregadas = false;
    }
    
    void Update()
    {
        /*if (db != null && infoCarregadas == false)
        {
            this.CarregaInfos();
        } else
        {
            if (infoCarregadas == false)
            {
                db = FirebaseAuthenticator.instance.fsDB;
            }
            
        }*/
    }

    private void CarregaInfos()
    {
        try
        {
            FirebaseFirestore db = FirebaseAuthenticator.instance.fsDB;
            var usuarioJson = PlayerPrefs.GetString("usuario");
            this.usuario = usuarioJson != "" ? JsonUtility.FromJson<Usuario>(usuarioJson) : null;
            if (this.usuario != null && this.usuario.UID != null)
            {
                this.usuarioCollection = db.Collection("usuario");
                DocumentReference docRef = this.usuarioCollection.Document(usuario.UID);
                docRef.GetSnapshotAsync().ContinueWith(task =>
                {
                    DocumentSnapshot snapshot = task.Result;
                    if (snapshot.Exists)
                    {
                        Dictionary<string, object> usuario = snapshot.ToDictionary();

                        foreach (KeyValuePair<string, object> pair in usuario)
                        {
                            if (pair.Key == "rank")
                            {
                                this.rankCollection = db.Collection("rank");
                                DocumentReference docRef = this.rankCollection.Document(pair.Value.ToString());
                                docRef.GetSnapshotAsync().ContinueWith(task =>
                                {
                                    DocumentSnapshot snapshot = task.Result;
                                    if (snapshot.Exists)
                                    {
                                        Dictionary<string, object> rank = snapshot.ToDictionary();

                                        foreach (KeyValuePair<string, object> pair in rank)
                                        {
                                            if (pair.Key == "nome")
                                            {
                                                this.rankNomeLabel.GetComponent<UnityEngine.UI.Text>().text = pair.Value.ToString();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Debug.Log("Erro ao carregar o rank: " + snapshot.Id);
                                    }
                                });
                            }
                        }
                    }
                    else
                    {
                        Debug.Log("Erro ao carregar o usuário: " + snapshot.Id);
                    }
                });
            }
            else
            {
                Debug.Log("Erro ao pegar usuário do PlayerPrefs");
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Erro: " + e);
        }
    }
}

文本鏈接到變量(打印波紋管)

在此處輸入圖像描述 在此處輸入圖像描述

this.rankNomeLabel.GetComponent<UnityEngine.UI.Text>().text = pair.Value.ToString(); in this line, the reference is null

認為問題在於在異步方法中設置值,但我不知道如何解決它

有誰知道發生了什么?

大多數 Unity API 只能在 Unity 主線程上使用(純結構除外,因為它們只是數據容器,不會立即依賴或影響實際場景)。

ContinueWith不保證在主線程中執行。

因此 Firebase 提供了擴展方法ContinueWithOnMainThread

ContinueWithOnMainThreae替換兩者或至少替換內部ContinueWith應該可以解決您的問題,或者至少可以更清楚地說明實際問題在哪里。


而不是一遍又一遍地使用GetComponent讓您的生活更輕松並直接使用正確的類型

using UnityEngine.UI;

...

public Text rankNomeLabel;
public Button botaoInfo;

這也確保您只能拖入實際連接了相應組件並且在運行時不易出錯的對象,因為它已經確保它不是null - 如果是(例如,如果 object 被破壞),您還可以立即在 Inspector 中查看

我通過在更新方法中檢查 boolean 解決了類似的問題。 這並不花哨,但它有效。

public class MyClass : MonoBehaviour
{
    private bool updateUI = false;

    private async Task function() {
        updateUI = true;
    }

    private void Update() {
        if (updateUI) {
            // update your ui here
            ...
            updateUI = false;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM