Using downloaded image as UI Image's source image?
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.
Answer by col000r · May 26, 2016 at 04:46 PM
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();
}
}
Your answer
Follow this Question
Related Questions
UnityEngine.UI and UnityEngine.EventSystem do not work, what do I do? 1 Answer
Better way to edit RawImage texture data?,Better way to edit a RawImage texture? 0 Answers
Android joystick doesn't work after 2nd level >.> 2 Answers
RectTransform Left Right Bottom Top 0 Answers
How Can i Get This bool to work? Just need someone willing to explain. 2 Answers