- Home /
Issue with UnityWebRequest
Hi everyone!
I made a game in which I can upload images from external folders. To do this, I used the WWW class. Now, the process works, but a warning appears saying: "WWW class is obsolete: Use UnityWebRequest, a fully featured replacement which is more efficient and has additional features". So I tried to replace WWW with UnityWebRequest, but it doesn’t work, and I can’t figure it out.
This is the code I used:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
public class FileManager : MonoBehaviour
{
string path;
public RawImage image;
public void OpenExplorer()
{
path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
GetImage();
}
void GetImage()
{
if (path != null)
{
UpdateImage();
}
void UpdateImage()
{
WWW www = new WWW("file:///" + path);
image.texture = www.texture;
}
}
}
Anyone can help me, please? Thank you so much!
Send to moderation because:
The provided code doesn't compile / doesn't make sense
The code does not represent the current state. It doesn't use UnityWebRequest as mentioned in the question.
The code seems to be a strange mix between editor code and runtime code.
Answer by rh_galaxy · Aug 06, 2019 at 03:47 PM
At least you should get an idea of how UnityWebRequest can be used... code is untested, but comes from a working script.
const string WEB_HOST = "file:///";
UnityWebRequest www;
Texture2D texture = null;
bool isDone = false;
public IEnumerator GetImage()
{
isDone = false;
string url = WEB_HOST + "D:/image.png";
www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
//retrieve result as binary
byte[] bytes = www.downloadHandler.data;
texture = new Texture2D(2, 2);
texture.LoadImage(bytes, false);
}
isDone = true;
}
int state = 0;
void Update()
{
if(state==0)
{
StartCoroutine(GetImage());
//set in the above, but since StartCoroutine returns before it has a chance
// to run we need to set it
bIsDone = false;
state++;
}
if(state==1)
{
if(bIsDone)
{
//texture is ready or has failed...
//...
}
}
}