I'm making an Android app that should, in the beginning, load data from a MySQL database and some images from the server. After that, the user will be in the outside, so the app will work offline.
I made the code to save all the database data (it works) and the image from the server to ApplicationPersistenceDataPath (not working). I already search for how I should do that. The code I have does not throw any error. But, when I tried to display it on the app the image was blank. That's when I looked in the folder where the images are being stored, and I cannot open them.
This is the method I have to save the images:
IEnumerator loadBgImage(string url, string file_name)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError || www.isHttpError)
{
print("erro");
}
else
{
string savePath = string.Format("{0}/{1}", Application.persistentDataPath, file_name);
if (!File.Exists(savePath))
{
System.IO.File.WriteAllText(savePath, www.downloadHandler.text);
}
}
}
}
And this is the code to show the image file in a Image:
string path = Application.persistentDataPath + "/" + nomeImagem;
imagem.GetComponent<SpriteRenderer>().sprite = LoadSprite(path);
This is the method called:
private Sprite LoadSprite(string path)
{
if (string.IsNullOrEmpty(path)) return null;
if (System.IO.File.Exists(path))
{
byte[] bytes = File.ReadAllBytes(path);
Texture2D texture = new Texture2D(900, 900, TextureFormat.RGB24, false);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage(bytes);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 8, 8), new Vector2(0.5f, 0.0f), 1.0f);
}
return null;
}
I really need to save the images first, and then display it offline. Can someone please tell me what I am doing wrong?
Update After following the suggestions on @derHugo's answer, this is the code I have to save images:
IEnumerator loadBgImage(string url, string file_name)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError || www.isHttpError)
{
print("erro");
}
else
{
var savePath = Path.Combine(Application.persistentDataPath, file_name);
var data = www.downloadHandler.data;
using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
{
fs.Write(data, 0, data.Length);
}
}
}
}
It works, but I still can't see the images when running the app. In the method to show the sprite I added the return of the created sprite.
Second Update
I follow again the suggestions of @derHugo, and I use rawImage instead of Image. And it's now working both on Unity editor and on Android device. This is the method I use:
private void LoadSprite(string path)
{
if (string.IsNullOrEmpty(path)) print("erro");
if (System.IO.File.Exists(path))
{
byte[] bytes = File.ReadAllBytes(path);
Texture2D texture = new Texture2D(900, 900, TextureFormat.RGB24, false);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage(bytes);
imagem.texture = texture;
}
}