Last active
February 28, 2022 08:11
-
-
Save yuujii/d99d0f7ebd9a76a6955a4facdeb3d299 to your computer and use it in GitHub Desktop.
Unity C# Pixabay API Search Images https://pixabay.com/ja/service/about/api/ #Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.Networking; | |
using UnityEngine.UI; | |
namespace Yu | |
{ | |
/// <summary> | |
/// Pixabay API - Search Images | |
/// <see href="https://pixabay.com/api/docs/">HERE</see> | |
/// </summary> | |
public class PixabayImageSearchExample : MonoBehaviour | |
{ | |
#region Public Variables | |
public Text SearchInput; | |
[System.Serializable] | |
public class PixabayResults | |
{ | |
public PixabayResult[] hits; | |
} | |
/// <summary> | |
/// Search Images | |
/// <see href="https://pixabay.com/api/docs/#api_search_images">HERE</see> | |
/// </summary> | |
[System.Serializable] | |
public class PixabayResult | |
{ | |
public string previewURL; | |
public int previewWidth; | |
public int previewHeight; | |
public string webformatURL; | |
public int webformatWidth; | |
public int webformatHeight; | |
public string largeImageURL; | |
public int imageWidth; | |
public int imageHeight; | |
} | |
#endregion | |
#region Private Variables | |
// getkey https://pixabay.com/ja/service/about/api/ | |
[SerializeField] | |
private string pixabay_apikey; | |
#endregion | |
void Start() | |
{ | |
} | |
IEnumerator getSearch(string q) | |
{ | |
UnityWebRequest www = UnityWebRequest.Get( | |
"https://pixabay.com/api/?key=" + pixabay_apikey + | |
"&q=" + q + | |
"&image_type=photo"+ | |
"&per_page=3" + // 3-200 Default: 20 | |
"&safesearch=1"); | |
yield return www.SendWebRequest(); | |
if (www.isNetworkError || www.isHttpError) | |
{ | |
Debug.Log(www.error); | |
} | |
else | |
{ | |
var res = JsonUtility.FromJson<PixabayResults>(www.downloadHandler.text); | |
Debug.Log(res.hits); | |
yield return getTexture(res.hits[0].largeImageURL); | |
} | |
} | |
IEnumerator getTexture(string image_url) | |
{ | |
UnityWebRequest www = UnityWebRequestTexture.GetTexture(image_url); | |
yield return www.SendWebRequest(); | |
if (www.isNetworkError || www.isHttpError) | |
{ | |
Debug.Log(www.error); | |
} | |
else | |
{ | |
Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture; | |
Renderer renderer = GetComponent<Renderer>(); | |
renderer.material.mainTexture = myTexture; | |
} | |
} | |
#region Event Handlers | |
public void DoSearch() | |
{ | |
var _t = SearchInput.text; | |
if (_t != "") | |
{ | |
StartCoroutine(getSearch(_t)); | |
} | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment