Skip to content

Instantly share code, notes, and snippets.

@JWardee
Last active January 25, 2016 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JWardee/269b5b78d00b7b3a1794 to your computer and use it in GitHub Desktop.
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)
using UnityEngine;
using System.Collections;
public class GeneralDirector : MonoBehaviour {
static public HTTP http;
public void Start () {
http = this.gameObject.GetComponent<HTTP> ();
}
}
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);
}
}
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