调用GetDownloadURLAsync()。ContinueWith时,脚本会结束(Google Firebase +资产捆绑下载)

时间:2019-02-22 20:18:18

标签: firebase unity3d firebase-authentication firebase-storage assetbundle

脚本新手,请耐心等待。

  • 在Unity 2018中工作
  • 使用Google Firebase存储+身份验证

在进行身份验证和随后获取资产捆绑包(远程存储在我们的Google Firebase存储设置中)期间,我设法将正确的,特定于用户的捆绑包正确下载到PC上的本地位置。

但是,当切换档并尝试通过UnityWebRequest将这些捆绑软件下载/缓存并存储在一个变量中时,我最终需要为我的脚本提供两倍于初始提示的内容,否则它只会到达此部分,然后认为自己已完成或由于缺少错误/错误而停滞不前:

在此之前:

  • 通过SignInWithEmailAndPasswordAsync.ContinueWith(任务等)在我的登录页面上输入并验证用户名和密码(这是两次的初始提示)
  • Firebase存储实例已创建
  • Firebase个人文件结构链接已创建
  • 将特定的捆绑包引用到变量中(prefab.ref就是这样的一种)
  • ...然后是这个:

    prefab_ref.GetDownloadUrlAsync().ContinueWith((Task<Uri> task1) =>
    {
        if (!task1.IsFaulted && !task1.IsCanceled)
        {
            Debug.Log("Download URL: " + task1.Result);
        }
        prefabDL_URL = task1.Result;
        Debug.Log("Task1 Result got stored!");
    });
    

此后,在Debug.Log之后,脚本将停止,没有错误或问题。在第二次按下登录按钮后,程序将继续,下载并存储捆绑包,并加载新的场景。我想知道如何迫使我的程序继续前进,而不是无缘无故地两次按下“登录”按钮。预先感谢大家!

我的完整脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using System.Threading.Tasks;
using UnityEngine.Networking;

public class EmailPasswordLogin : MonoBehaviour
{
    private FirebaseAuth auth;
    public InputField UserNameInput, PasswordInput;
    public Button LoginButton;
    public Text ErrorText;
    public string uri;
    public System.Uri prefabDL_URL;

    public Firebase.Storage.StorageReference prefab_outerRef;
    public Firebase.Storage.StorageReference vuforia_outerRef;

    public AssetBundle prefabBndl;
    public AssetBundle vuforiaBndl;

    private void Start ()
    {
        //Establish instance of Firebase Authentication
        auth = FirebaseAuth.DefaultInstance;
        //Pre-fill the User/Password inputs for easy testing
        UserNameInput.text = "MY USERNAME";
        PasswordInput.text = "MY PASSWORD";

        //Run the Login method when the LoginButton is pressed, taking the inputs
        LoginButton.onClick.AddListener(() => Login(UserNameInput.text, PasswordInput.text));
    }

    //Our main method, takes in User and Password for Authentication and subsequent Bundle downloading
    public void Login(string email, string password)
    {
        //Runs Firebase's Authentication Async-style, storing the result in a User variable and displaying this info to the Console
        auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
        {
            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithEmailAndPasswordAsync canceled.");
                return;
            }

            if (task.IsFaulted)
            {
                Debug.LogError("SignInWithEmailAndPasswordAsync error: " + task.Exception);
                if (task.Exception.InnerExceptions.Count > 0)
                {
                    UpdateErrorMessage(task.Exception.InnerExceptions[0].Message);
                }
                return;
            }
            FirebaseUser user = task.Result;
            Debug.LogFormat("User signed in successfully: ({0}) ({1})", user.DisplayName, user.UserId);
            PlayerPrefs.SetString("LoginUser", user != null ? user.Email : "Unknown");

            //DOWNLOAD YOUR ASSET FILES RIGHT IN HERE\\

            //Reference to ALL of Storage
            Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance; 

            //Reference to my specific file under the current UserId
            Firebase.Storage.StorageReference prefab_ref = storage.GetReferenceFromUrl("[FILE STRUCTURE PREFIX]" + user.UserId + "[FILE STRUCTURE SUFFIX]");
            Firebase.Storage.StorageReference vuforia_ref = storage.GetReferenceFromUrl("[FILE STRUCTURE PREFIX]" + user.UserId + "[FILE STRUCTURE SUFFIX]");

            //Store the specific file in a variable for use outside of the Method
            prefab_outerRef = prefab_ref;
            vuforia_outerRef = vuforia_ref;

            //Acquire the URI for one specific file
            prefab_ref.GetDownloadUrlAsync().ContinueWith((Task<Uri> task1) =>
            {
                if (!task1.IsFaulted && !task1.IsCanceled)
                {
                    Debug.Log("Download URL: " + task1.Result);
                }
                prefabDL_URL = task1.Result;
                Debug.Log("Task1 Result got stored!");
            });

            //Shoot this URI as a String to the Console, then run a Coroutine to acquire the Bundle from the URI
            Debug.Log(prefabDL_URL.ToString());
            StartCoroutine(GetBundle(prefabDL_URL));
            //UnityWebRequestAssetBundle.GetAssetBundle(prefab_ref.ToString(), 1, 0);

            //DOWNLOAD YOUR ASSET FILES RIGHT IN HERE\\

            //Load the following scene once things are downloaded and stored
            SceneManager.LoadScene("Main");
        });
    }


    //Our Coroutine for acquring the actual bundle file, taking in the stored URI and using it to download via UnityWebRequestAssetBundle
    IEnumerator GetBundle(Uri uri)
    {
        using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(uri, 1, 0))
        {
            yield return uwr.SendWebRequest();

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log(uwr.error);
            }
            else
            {
                //Get the content and store it in our pre-established Bundle variable, then talk to Console about it.
                prefabBndl = DownloadHandlerAssetBundle.GetContent(uwr);
                Debug.Log("We've got a bundle stored!");
            }
        }
    }

    //Update our Error Message
    private void UpdateErrorMessage(string message)
    {
        ErrorText.text = message;
        Invoke("ClearErrorMessage", 3);
    }

    //Blank out our Error Message
    void ClearErrorMessage()
    {
        ErrorText.text = "";
    }
}

0 个答案:

没有答案