Hello, How are you?
This is my objective, I need to load an image from an URL from Remote Config. But a twist to this assignment was that we were to save the image we loaded from the URL. If there was an internet connection then the can be loaded from the URL but if there I no internet connection then the last saved image should be displayed.
This was my script but the problem is it does not work on Android
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class ImageDownloader : MonoBehaviour
{
public string imageUrl = "https://example.com/image.jpg";
public void Initialize()
{
this.gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>(Application.dataPath + "/Assets/BackgroundImage.png");
}
public IEnumerator DownloadAndSaveImage()
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(imageUrl);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Failed to download image: " + request.error);
yield break;
}
else{
Texture2D texture = DownloadHandlerTexture.GetContent(request);
byte[] imageBytes = texture.EncodeToPNG();
Destroy(texture);
string savePath = Application.dataPath + "/Assets/BackgroundImage.png";
System.IO.File.WriteAllBytes(savePath, imageBytes);
Sprite downloadedSprite = LoadSpriteFromPath(savePath);
this.gameObject.GetComponent<Image>().sprite = downloadedSprite;
Debug.Log("Image downloaded and saved to: " + savePath);
}
}
private Sprite LoadSpriteFromPath(string imagePath)
{
byte[] imageBytes = System.IO.File.ReadAllBytes(imagePath);
Texture2D texture = new Texture2D(2, 2);
if (texture.LoadImage(imageBytes))
{
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
return sprite;
}
else
{
Debug.LogError("Failed to load image as Sprite: " + imagePath);
return null;
}
}
private void Start()
{
StartCoroutine(DownloadAndSaveImage());
}
}
This works great in the editor but when I build it to an app and tested it, it does not change the image when changing the URL on Remote Config.
Please help, Thanks