Last active
March 19, 2020 13:34
-
-
Save Kogarasi/9689cc3a5f0df7f9bf4b1b0266defdc5 to your computer and use it in GitHub Desktop.
IPアドレスから住んでいる地域を確認するサンプル for 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; | |
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; | |
} | |
} |
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; | |
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