Skip to content

Instantly share code, notes, and snippets.

@Kogarasi
Last active March 19, 2020 13:34
Show Gist options
  • Save Kogarasi/9689cc3a5f0df7f9bf4b1b0266defdc5 to your computer and use it in GitHub Desktop.
Save Kogarasi/9689cc3a5f0df7f9bf4b1b0266defdc5 to your computer and use it in GitHub Desktop.
IPアドレスから住んでいる地域を確認するサンプル for Unity
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class KResistance: MonoBehaviour {
private const string apiUrl = "https://ipinfo.io/json";
[System.Serializable]
public class Response {
public string ip;
public string hostname;
public string city;
public string region;
public string country;
public string loc;
public string org;
public string postal;
public string timezone;
public string readme;
}
private Response response;
static public KResistance Create(){
var go = new GameObject( "KResistance" );
var component = go.AddComponent<KResistance>();
return component;
}
IEnumerator Start(){
var request = UnityWebRequest.Get( apiUrl );
yield return request.SendWebRequest();
if( request.isHttpError || request.isNetworkError ){
throw new Exception( request.error );
}
response = JsonUtility.FromJson<Response>( request.downloadHandler.text );
}
public bool IsReady(){
return response != null;
}
public bool Check( string region = "Kagawa" ){
if( response == null ){
throw new NullReferenceException();
}
return response.region == region;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sample : MonoBehaviour
{
// Start is called before the first frame update
IEnumerator Start()
{
var resistance = KResistance.Create();
while( !resistance.IsReady() ){
yield return null;
}
Debug.Log( resistance.Check() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment