How to download image from firebase database, and load it into image in unity

故事扮演 提交于 2020-01-03 05:33:31

问题


I use Firebase Realtime database to handle some of the UI in my Unity mobile application. I save and retrieve data from my database without any problems. The problem comes when i want to load an image from Firebase Storage. I have saved the URL's and names of the images' on my server, and now i try to Instantiate a prefab. This prefab contains a panel with text and an image for each Firebase-child. The structure of the image i try to load from my database looks like this:

So in my code I go to the child "Byer", find the first name and add the key as the name of my newly instantiated prefab works fine. But when I try to load the imageURL into the image, I get the trouble - my code looks like this:

DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
FirebaseDatabase.DefaultInstance.GetReference("Byer").ChildAdded += Handle_ChildAdded;


 void Handle_ChildAdded(object sender, ChildChangedEventArgs e)
    {
        if (e.Snapshot.Value != null)
        {
            var dict = e.Snapshot.Value as Dictionary<string, object>;


           Transform scrollViewObj = Instantiate(prefab, new Vector3(0, (downSize * Global.citiesCount) - firstY, 0), Quaternion.identity);
           scrollViewObj.transform.Find("Text").gameObject.GetComponent<Text>().text = e.Snapshot.Key;
               scrollViewObj.name = e.Snapshot.Key;

//HERE I TRY TO LOAD IMAGE FROM URL (This is my problem)
            string data_URL = dict["ImageURL"] as string;
            //Start coroutine to download image
            StartCoroutine(AccessURL(data_URL, scrollViewObj.transform.Find("Image").gameObject.GetComponent<Image>()));

                }
            }

//Function to download (This could might also be my problem)
      IEnumerator AccessURL(string url, Image img)
        {


        //Debug.Log("Accessing texture URL in database");
        using (WWW www = new WWW(url))
        {

            yield return www;
            Renderer r = GetComponent<Renderer>();
            r.material.mainTexture = www.texture;
            img.material.mainTexture = www.texture;
            Debug.Log("Texture URL: " + www.url);
        }
    }

Can anyone see what I am doing wrong?


回答1:


  • Make sure you imported FirebaseStorage.unitypackage
  • You will need StorageReference not DatabaseReference

    Firebase.Storage.StorageReference storageReference = 
       Firebase.Storage.FirebaseStorage.DefaultInstance.GetReferenceFromUrl("storage_url");
    
    storageReference.Child("resource_name").GetBytesAsync(1024*1024).
        ContinueWith((System.Threading.Tasks.Task<byte[]> task) =>
        {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                byte[] fileContents = task.Result;
                Texture2D texture = new Texture2D(1, 1);
                texture.LoadImage(fileContents);
                //if you need sprite for SpriteRenderer or Image
                Sprite sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f,texture.width, 
                texture.height), new Vector2(0.5f, 0.5f), 100.0f);
                Debug.Log("Finished downloading!");
            }
        });
    
  • storage_url: Found in firebase->storage section. will be something like gs://project_name.appspot.com/

  • resource_name : Name of a resource like image_name.png


来源:https://stackoverflow.com/questions/53938004/how-to-download-image-from-firebase-database-and-load-it-into-image-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!