This has been bothering me for awhile and I can’t figure it out.
Basically what the IEnum of the script does, and what I know how to do:
- Use a WWW to get a list of image names returned to it via PHP. [Yield]
- Split the Names list into an array.
- Count the array
- For loop to instantiate a button prefab of a button object with an image child for each image. [Yield]
- Use another for loop and WWW again to download each image. [Yield]
That’s where I get stuck. Step 6 would be to load the downloaded images with the IEnumerator to the source image of each UI.Image.
I’ve seen a few questions on this and did my homework on it for awhile now. None of them address downloading the images, but rather loading them from the resources folder. I know that I could use OnGUI to do it easily, but most of the answers of my previous questions has warned against using OnGUI.
All you need to do is load the downloaded image into a texture and then create a sprite from that texture:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DownloadAndDisplay : MonoBehaviour {
public Image img;
IEnumerator Start () {
WWW www = new WWW("http://gameassets.net/GameAssetsLogo.png");
yield return www;
img.sprite = Sprite.Create( www.texture, new Rect( 0f, 0f, www.texture.width, www.texture.height ), new Vector2( 0.5f, 0.5f ) );
img.SetNativeSize();
}
}
If you use UI.RawImage instead of UI.Image it’s even easier, because then you can just assign the Texture directly and don’t have to turn it into a Sprite:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DownloadAndDisplay : MonoBehaviour {
public RawImage img;
IEnumerator Start () {
WWW www = new WWW("http://gameassets.net/GameAssetsLogo.png");
yield return www;
img.texture = www.texture;
img.SetNativeSize();
}
}