c#


Load image from URL


I'm trying to load an image from url to GameObject.
I found the next tutorial:
https://www.youtube.com/watch?v=8UK2EsKBzv8
The download succeeded, but I can't see the image.
What am I doing wrong?
// Use this for initialization
void Start () {
StartCoroutine(loadSpriteImageFromUrl("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png"));
}
IEnumerator loadSpriteImageFromUrl(string URL)
{
// Check internet connection
if (Application.internetReachability == NetworkReachability.NotReachable)
{
yield return null;
}
var www = new WWW(URL);
Debug.Log("Download image on progress");
yield return www;
if (string.IsNullOrEmpty(www.text))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
Sprite sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height),
Vector2.one / 2);
GetComponent<SpriteRenderer>().sprite = sprite; // Change current sprite
}
}
EDIT
After moving as suggested from ScriptRenderer to UI Image, the code looks like this:
IEnumerator loadSpriteImageFromUrl(string URL, GameObject cell)
{
// Check internet connection
if(Application.internetReachability == NetworkReachability.NotReachable)
{
yield return null;
}
var www = new WWW(URL);
Debug.Log("Download image on progress");
yield return www;
if(string.IsNullOrEmpty(www.text))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
Sprite sprite = Sprite.Create(texture,
new Rect(0,0, texture.width, texture.height),
Vector2.one/2);
cell.AddComponent<Image>();
cell.GetComponent<Image>().sprite = sprite;
}
}
But I'm getting next result to the screen (and not the image in the url):
Your code is fine. The downloaded Image is not showing because you are in the Scene-View and the camera is away from it.
Select the GameObject the script is attached to then press F. It should zoom into it and you will see the downloaded image. See here for how to reset your Unity layout to get the Game-View back.
If you still can't see the image then the SpriteRenderer is not in front of the camera. From the screenshot, its position is 0,0,0 so make sure that the camera's position is 0,0,-10.
The right Way to Display Image:
To simply display image in Unity, use the Image or RawImage component. RawImage is recommended since it doesn't generate garbage when changing the Texture. You should already know how to di this from th
If you need to attach Rigidbody or 2D Colliders to that Image then use SpriteRenderer or MeshRenderer for 3D Objects to display the image.
These are the four ways to display an image in Unity. #2 is recommended if no physics or collision is needed at-all:
1.With the Image Component:
public Image imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";
void Start()
{
StartCoroutine(loadSpriteImageFromUrl(url));
}
IEnumerator loadSpriteImageFromUrl(string URL)
{
WWW www = new WWW(URL);
while (!www.isDone)
{
Debug.Log("Download image on progress" + www.progress);
yield return null;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
Sprite sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height), Vector2.zero);
imageToDisplay.sprite = sprite;
}
}
There have been problems with LoadImageIntoTexture in the past. For this reason, my other examples won't use LoadImageIntoTexture. If you see a question mark as the Image then use www.bytes with the Texture2D.LoadImage function.
Simply replace:
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
with
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(www.bytes);
texture.Apply();
2.With the RawImage Component(Recommended):
public RawImage imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";
void Start()
{
StartCoroutine(loadSpriteImageFromUrl(url));
}
IEnumerator loadSpriteImageFromUrl(string URL)
{
WWW www = new WWW(URL);
while (!www.isDone)
{
Debug.Log("Download image on progress" + www.progress);
yield return null;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(www.bytes);
texture.Apply();
imageToDisplay.texture = texture;
}
}
3.With the SpriteRenderer Component:
Mostly used for 2D Objects and 2D physics simulation with Rigidbody2D and 2D Colliders. If not then use the UI(#1 or #2) above.
public SpriteRenderer imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";
void Start()
{
StartCoroutine(loadSpriteImageFromUrl(url));
}
IEnumerator loadSpriteImageFromUrl(string URL)
{
WWW www = new WWW(URL);
while (!www.isDone)
{
Debug.Log("Download image on progress" + www.progress);
yield return null;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
Sprite sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height), Vector2.zero);
imageToDisplay.sprite = sprite;
}
}
4.With the MeshRenderer Component:
Mostly used for 3D Objects and 3D physics simulation with Rigidbody and 2D Colliders. If not then use the UI(#1 or #2) above. Just a use a Plane, Quad or a Cube with a MeshRenderer.
public MeshRenderer imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";
void Start()
{
StartCoroutine(loadSpriteImageFromUrl(url));
}
IEnumerator loadSpriteImageFromUrl(string URL)
{
WWW www = new WWW(URL);
while (!www.isDone)
{
Debug.Log("Download image on progress" + www.progress);
yield return null;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
imageToDisplay.material.mainTexture = texture;
}
}

Related Links

Trying to build a procedure to create a variable but it gets trapped inside
Write to file with FileStream without using “using”
Unable to run Enable-Migration VS2013 SP4
ViewBag is passing changed value PartialView
Serializing a field with protobuf results in a 0 bytes data file
BDD Specflow - Scenario Outline where text spans multiple lines
Shared SQL Database on UNC Share with Entity Framework
CodeFirst mapping relationship between entities
Create user friendly public/private key pairs
How to cache the image of the control?
ValidationMessageFor automatically getting fred
Generic Type instance with anonymous type as generic argument, how to convert back to original type properly?
Passing an object to constructor when using StructureMap 3
MVC Model, how to put Error Message in model without using Requried or Compare attribute?
Find Average of a node in Multiple JSON strings
Nhibernate ArgumentNullException was unhandled Value cannot be null Parameter name: stream

Categories

HOME
joomla
redux
teradata
cxf
pelican
phantomjs
ebay-api
hex
localhost
sdk
flowtype
hibernate-mapping
expo
tag-cloud
taxonomy
bug-reporting
screen-scraping
ios9
lines
directions
scene7
javax
wunderground
kdevelop
multi-user
mongoid5
redhat-brms
libconfig
iterm2
file-conversion
runner
jsfl
import.io
audio-fingerprinting
nservicebus6
webmatrix
xamarin-test-cloud
chain
bipartite
acceleo
firebase-job-dispatcher
toggleclass
easy68k
konakart
airwatch
hotkeys
aws-kms
angular-i18n
bbedit
music-player
wordpress-plugin
web-performance
ruby-1.8.7
jain-sip
fileinputstream
esb-toolkit-2.1
asp.net-2.0
connection-timeout
optimistic-locking
fiware-health
quickfixn
system.io.packaging
lwuit
angular-file-upload
email-headers
kernel-density
codio
surfaceview
ie-developer-tools
pechkin
extensibility
leap-year
asp.net-4.0
removeall
simplemembership
nude.js
maven-eclipse-plugin
openwrap
opendir
zipstream
nbehave
s60
datarelation
chromebug
pitch-shifting
linq-to-mysql
qprocess
carbon-emacs
pkcs#7

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile