Lasse Bickmann
Lasse Bickmann

Reputation: 133

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

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:

enter image description here

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?

Upvotes: 1

Views: 5485

Answers (1)

Jay Rojivadiya
Jay Rojivadiya

Reputation: 31

  • 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

Upvotes: 2

Related Questions