Recently I needed a script though which I could easily get and send data to a REST Server. I picked my fav environment: MEAN. using Yeoman, I quickly implemented a simplistic REST Server, which will serve all data for my Unity WebPlayer Build. So here goes my take on a simple REST Utility for Unity.
Recently I needed a script though which I could easily get and send data to a REST Server. I picked my fav environment: MEAN. using Yeoman, I quickly implemented a simplistic REST Server, which will serve all data for my Unity WebPlayer Build. So here goes my take on a simple REST Utility for Unity.
NOTE:
Since UNity 5.3, the in-built REST client, httpwebrequest is really good and hence, you won’t be needing this tool at all. For below versions, you can use this code.
Unity has the wonderful WWW utility through which we can GET or POST data to/from any REST Server. After stumbling upon further, I found a StackOverflow post for a Simple GET/POST Wrapper for REST Utility for Unity.
I tweaked it a little ( added Callbacks instead of directly returning values) and use din my projects and it worked like a charm. And yes, for those who were concerned if it will work for WebBuilds, well, Yes, it works. I have Tested it. The following is the code:
/// /// Gets JSON data from the specified URL. /// /// The URL. /// The callback. publicvoidGET(string url, System.Action) { WWW www = new WWW(url); StartCoroutine(WaitForRequest(www, Callback)); }
/// /// Gets a texture form the specified URL. /// /// The URL. /// The callback. publicvoidGETTexture(string url, System.Action) { WWW www = new WWW(url); StartCoroutine(WaitForRequest(www, Callback, true)); }
/// /// GETs an asset from Asset Bundle /// /// The Url to fetch the Asset from /// Asset Name /// The Callback that contains the GameObject as its parameter publicvoidGETAsset(string url, string AssetName, System.Action) { StartCoroutine(WaitForAsset(url, AssetName, Callback)); }
/// /// Posts a Form data to the specified URL. /// /// The URL. /// The post. /// The callback. ///UnityEngine.WWW. public WWW POST(string url, Dictionary<string, string> post, System.Action) { WWWForm form = new WWWForm(); foreach (KeyValuePair post_arg in post) { form.AddField(post_arg.Key, post_arg.Value); } WWW www = new WWW(url, form);
using System; using System.Collections; using System.Collections.Generic; using SimpleJSON; using Object = System.Object; using D3VRestWrapper; publicclassmain : MonoBehaviour { D3VRest db; Texture2D boxTex; GameObject box; // Use this for initialization voidStart() { db = GameObject.Find("DB").GetComponent(); FetchJackpot(); FetchTexure(); } /// /// Fetches the texure. /// publicvoidFetchTexure() { db.GETTexture("http://localhost:3000/textures/playBtn.png", delegate(object data) { boxTex=data as Texture2D; GameObject.Find("Quad").renderer.material.mainTexture=boxTex; FetchT(); }); } /// /// Fetches the jackpot. /// publicvoidFetchJackpot() { db.GET("http://localhost:3000/jackpot", delegate(Object data) { //Data has been Received. Lets convert the returned object to JSON data var www = JSON.Parse(data.ToString()); //CHeck if Error is present or not. ( and hopefully not!) if (!www["err"].AsBool) { //Check if data is present or not if (www["data"] != null && www["data"]["score"] != null) { print("Score: " + www["data"]["score"].Value); GameObject.Find("lblJackpot").GetComponent().text = "Jackpot: " + www["data"]["score"].Value; } else Debug.LogWarning("Score: 0"); } else { Debug.LogError("Error Occured! : " + www["err"].ToString()); } }); } /// /// Updates the jackpot. /// publicvoidUpdateJackpot() { //Prepare Data to be Sent Dictionary<string, string> form = new Dictionary<string, string>(); form.Add("score", GameObject.Find("inpJackpot").GetComponent().value); //Send the data db.POST("http://localhost:3000/jackpot", form, delegate(Object data) { var www = JSON.Parse(data.ToString()); if (!www["err"].AsBool) { FetchJackpot(); Debug.Log("Score Updated!"); } else { Debug.LogError("Error Occured! : " + www["err"].ToString()); } }); } publicvoidFetchT() { db.GETAsset("localhost:3000/prefabs/t1.unity3d", "t1", delegate(Object data) { box = Instantiate((UnityEngine.Object)data) as GameObject; box.renderer.material.mainTexture = boxTex; }); } }
Genrally, this simple REST utility for unity could be enhanced more and JSON can be integrated as well. I will leave this upto you. Or may be I will find out time to add more features to it and add it to my very own Utility Library ( _unity).