Hii, I am working on one project in which I want to randomly display wallpapers from API. in that project I set one random. range the select one random number and on that number, all data and wallpaper are rendered in unity. I can do and the data get displayed but I can’t get images.
Does anyone help me with this?
I can able to display one wallpaper from this script but i cant able to display random wallpaper from API URLs
Here is my code:
public class imageRender : MonoBehaviour
{
public string TextureURL ;
// instance the script
public static imageRender instance;
//for wallpaper id
public int randomwallpaperid;
//refernce from api
public string Artistname;
public string Descrption;
public string urls;
public string tmpName = “Temp name”;
public string Titles;
public Text titleendered;
public Text artistrenderer;
public Text descrptionrendered;
private void Start()
{
instance = this;
StartCoroutine(DownloadImage(TextureURL));
}
public void Update()
{
randomiD();
}
void randomiD()
{
randomwallpaperid = Random.Range(0, 495);
}
public void wallpaperdetailsgetin()
{
wallpaperdetails walldetils = new wallpaperdetails()
{
wallpaper_id = randomwallpaperid,
};
StartCoroutine(wallpaperdatasync(walldetils));
Debug.Log(walldetils.wallpaper_id);
}
public IEnumerator wallpaperdatasync(wallpaperdetails wallpapdetails )
{
WWWForm form = new WWWForm();
form.AddField(“wallpaper_id”, randomwallpaperid);
using (UnityWebRequest wallpaperwebrequest = UnityWebRequest.Post(“Xenbu”, form))
{
yield return wallpaperwebrequest.SendWebRequest();
if (wallpaperwebrequest.result != UnityWebRequest.Result.Success)
{
Debug.Log(wallpaperwebrequest.error);
}
else
{
SceneManager.LoadScene(“imagescene”);
var jsonString = wallpaperwebrequest.downloadHandler.text;
Debug.Log(jsonString);
Debug.Log("data get " + wallpaperwebrequest.downloadHandler.text);
var user1 = JsonConvert.DeserializeObject(wallpaperwebrequest.downloadHandler.text);
Debug.Log(user1.message);
Debug.Log(user1.data.title);
Titles = user1.data.title;
Artistname = user1.data.artist_name;
Descrption = user1.data.description;
titleendered.text = Titles;
artistrenderer.text = Artistname;
descrptionrendered.text = Descrption;
urls = user1.data.url;
// Debug.Log(user1.data.free_url);
//Debug.Log(Titles);
// Debug.Log(Artistname);
// Debug.Log(Descrption);
// Debug.Log(user1.data);
}
}
}
IEnumerator DownloadImage(string MediaUrl)
{
Debug.Log(urls);
UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
Debug.Log(request.error);
else
{
Texture2D webTexture = ((DownloadHandlerTexture)request.downloadHandler).texture as Texture2D;
Sprite webSprite = SpriteFromTexture2D(webTexture);
gameObject.GetComponent().sprite = webSprite;
}
}
Sprite SpriteFromTexture2D(Texture2D texture)
{
return Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);
}
}