APITest.cs
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using SimpleJSON;
using System;
public class APITest : MonoBehaviour
{
private const string BaseUrl = "https://api.gamification.oshimodev.xyz/api/";
private string token;
private string username;
private string password;
[SerializeField] private AudioClip[] audioClips;
private IEnumerator Start()
{
yield return StartCoroutine(InitializeUser());
yield return StartCoroutine(SilentLogin());
yield return StartCoroutine(GetUserOshiStatus());
}
private IEnumerator InitializeUser()
{
using (UnityWebRequest www = UnityWebRequest.Post(BaseUrl + "users/initialize", ""))
{
yield return www.SendWebRequest();
HandleResponse(www, jsonResponse =>
{
username = jsonResponse["username"];
password = jsonResponse["password"];
});
}
}
private IEnumerator SilentLogin()
{
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("password", password);
using (UnityWebRequest www = UnityWebRequest.Post(BaseUrl + "users/silent-login", form))
{
yield return www.SendWebRequest();
HandleResponse(www, jsonResponse => token = jsonResponse["access_token"]);
}
}
private IEnumerator GetUserOshiStatus()
{
using (UnityWebRequest www = UnityWebRequest.Get(BaseUrl + "user-oshi-status/one-user-oshi-status"))
{
www.SetRequestHeader("Authorization", "Bearer " + token);
yield return www.SendWebRequest();
HandleResponse(www, jsonResponse =>
{
var waitMotionList = jsonResponse["wait_motion_list"];
var motionList = waitMotionList["top_wait_motion_list"].Count > 0 ? waitMotionList["top_wait_motion_list"] : waitMotionList["skinship_wait_motion_list"];
var randomMotion = motionList[UnityEngine.Random.Range(0, motionList.Count)];
PlayAudioClip(randomMotion["wait_motion_voice_addressable_key"]);
});
}
}
private void HandleResponse(UnityWebRequest www, Action<JSONNode> onSuccess)
{
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
onSuccess(JSON.Parse(www.downloadHandler.text));
}
}
private void PlayAudioClip(string clipName)
{
var audioClip = Array.Find(audioClips, clip => clip.name == clipName) ?? Array.Find(audioClips, clip => clip.name == "default");
if (audioClip != null)
{
Debug.Log(audioClip.name);
AudioSource.PlayClipAtPoint(audioClip, Vector3.zero);
}
}
}
Comments
Post a Comment