Skip to content

Instantly share code, notes, and snippets.

@JWardee JWardee/GeneralDirector.cs
Last active Jan 25, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.