Search code examples
c#unity-game-enginerawimage

Unity. After downloading my rawimage is still blank


Hi My scene name is a game.In that scene I am having A main panel that's name is ITEMCONTAINER. In item container I am having a panel whoes name is ITEM. I attached a script in ITEM PANEL. IN that script i am having a game object public,a raw image ,text and how many times loop will continue are public. In the place of game object i attached my prefab,that contain 1 text and 2 rawimage. in place of text i attached text component of prefab and same like raw image. When I run the game the text value I am getting correctly but rawimage is showing blank in runtime.Here i am running my loop 3 times and all three times it create clone of my prefab panel as a child in itempanel I want rawimage dynamic at my run time

output

enter image description here

prefab

enter image description here

  1. image= in this image , it contains output.here rawimage is blank but text valuecoming perfectly

  2. image = it is my prefab that prefab will be clone during runtime, here it shows image but during runtime , in clone it shows blank

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;   
    using UnityEngine.UI;    
    public class DynamicData : MonoBehaviour {      
    public GameObject prefab; 
    public Text name;       
    public int numberToCreate;
    
    public RawImage profile;
    
    
    void Start () {
    
        for (int i = 0; i < numberToCreate; i++)
        {
            name.text = "a"+i;
            StartCoroutine( ImageDownload( profile));
    
            Instantiate <GameObject>(prefab, transform);
        }
    
    }
    IEnumerator ImageDownload ( RawImage img) {
    
        WWW www = new WWW("https://www.w3schools.com/w3images/fjords.jpg");
    
        yield return www;
    
        Texture2D texure = new Texture2D (1, 1);
        texure.LoadImage (www.bytes);
        texure.Apply ();
        img.texture = texure;
    
    }
    

    }


Solution

  • You are assigning the downloaded image to the profile variable which is not a variable from the instantiated Object. In the loop, you need to get the child of each instantiated Object with transform.Find("profile") then get the RawImage component attached to it with GetComponent and pass it to the ImageDownload function.

    Replace your for loop with this:

    for (int i = 0; i < numberToCreate; i++)
    {
        name.text = "a" + i;
    
        GameObject instance = Instantiate<GameObject>(prefab, transform);
        //Get RawImage of the current instance
        RawImage rImage = instance.transform.Find("profile").GetComponent<RawImage>();
        StartCoroutine(ImageDownload(rImage));
    }
    

    Please rename public Text name; to something else like public Text userName; because the name is already declared in MonoBehavior you derived your script from.