Last active
January 25, 2016 16:28
-
-
Save JWardee/269b5b78d00b7b3a1794 to your computer and use it in GitHub Desktop.
Helper class for executing a HTTP request using c# in Unity v5 by calling one function and supplying a callback (very similarly to jQuery)
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 UnityEngine; | |
using System.Collections; | |
public class GeneralDirector : MonoBehaviour { | |
static public HTTP http; | |
public void Start () { | |
http = this.gameObject.GetComponent<HTTP> (); | |
} | |
} |
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 UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class HTTP : MonoBehaviour { | |
public void New(string url, Action<string> callback, Dictionary<string, string> fields) { | |
StartCoroutine(MakeRequest(url, callback, fields)); | |
} | |
public void New(string url, Action<string> callback) { | |
New(url, callback, null); | |
} | |
private IEnumerator MakeRequest(string url, Action<string> callback, Dictionary<string, string> fields) { | |
WWWForm data = new WWWForm (); | |
if (fields != null) { | |
foreach (var field in fields) { | |
data.AddField (field.Key, field.Value); | |
} | |
} | |
WWW www = new WWW(url, data); | |
yield return www; | |
Debug.Log ("Request sent!"); | |
callback.Invoke (www.text); | |
} | |
} |
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 UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class Main : MonoBehaviour { | |
public void Start() { | |
// BASIC GET REQUEST | |
// Make HTTP request to the url and call the "callback" function when complete | |
GeneralDirector.http.New ("http://mysite.com", callback); | |
// BASIC POST REQUEST | |
Dictionary<string, string> fields = new Dictionary<string, string> (); | |
fields.Add ("name", "James"); | |
fields.Add ("score", "100"); | |
// Make HTTP request to url including "fields" as POST variables, | |
// once complete the "callback" function is invoked | |
GeneralDirector.http.New ("http://mysite.com", callback, fields); | |
} | |
public void callback(string result) { | |
Debug.Log("Response: "+result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment