How to make HTTP GET/POST Requests in Unity 5 C#

Recently I have been doing a lot with GET and PUT requests to get JSON data from a server. Throughout my time working on this project, I noticed that the examples provided by Unity for using the WWW class for POST headers, is geared more towards SQL databases, and they make a lot of assumptions about your server configuration.

Why use the WWW class?

There a tons of ways to make HTTP requests in C#, like the HttpRequest Class for example. But, there is a huge problem with using classes like these at run time in Unity, and that is they run on the main thread. This means that if the thing that you a requesting is large enough (which it really doesn’t need to be that big), it can cause some pretty bad frame rates. Even if you put the request in a co-routine, then you if things fail it can get pretty complicated to handle things how you want to. Or if there is a timeout to the server, or a bad request, then everything could come crashing down.

The WWW class has several features about it that are useful. First of all, it is built into Unity, so you have that without having to look at a bunch of different documentations. The WWW class handles all the back end stuff for you, like opening and closing the data streams, with much less code. Finally, the WWW class runs on a separate thread! This means increased performance, and less chance of things hanging up your frame rate.

How to implement the WWW class

The WWW class is simple and easy to use, but you will need a couple things first if you want to make a POST request with it.

  1. A database set up on a server, whether it is SQL, ELK, or whatever other back end you want. This needs to be configured before you can do anything.
  2. Make sure that the firewall that is configured on the server will allow you to access the port or service that you need. This sounds obvious but it can cause a lot of frustration if you don’t catch it early.
  3. A Unity project that is hungry for some JSON data!

Here is a co-routine that will make a request, and wait for it to finish before moving along.

private IEnumerator PostJsonData(){
 // The URL of the server, and the port
 string url = "http://<myURL>:<my Port>";

 // The query that you want to send, read in from the streaming assets
 // This way we can just read in the Query once and reference it
 string query = System.IO.File.ReadAllText(Application.streamingAssetsPath + "/myQuery.json");

 // Create HTML headers
 Dictionary<string, string> headers = new Dictionary<string, string>();

 // Set the headers to be JSON format
 headers["Content-Type"] = "application/json";

 // Get the post data that I will be using, and encode it properly
 byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(query);

 // Create a web request object
 WWW myRequest = new WWW(url, postData, headers);

 // Yield until it's done:
 yield return myRequest;

 // Check if there was an error or not
 if(myRequest.error ==null)
 // There was no error, you have your data!
 // Send that data to the Json Utility and get it parsed in a C# data object
 string jsonDataString = myrequest.text;

 // Handle there being an error
 Debug.Log("There was an error in the request");

Now that you have your JSON data in string format, you can use Unity’s JSON Utility class to turn it into a C# data object. I have another post about doing that here.

If you are interested in how to do this specifically with the ELK stack, then fear not! I have more posts about that coming, with specific instructions on how to configure it. For now I made a GitHub repo with a couple useful things for creating a CentOS 7 ELK stack.

Using Unity 5.5.1

Random Distribution Demo

Random Distribution Demo on GitHub

random demo screen capThis is a school project that I did a lot more than I had to do. The main goal of this project is to show my understanding of using different random distributions in code.

I used Perlin noise to generate the terrain, and I can change it to whatever kind of shape I want just in the editor. For the dinosaurs, I used a non-uniform distribution to make it so that there are more towards the front, and less in the back. The leaders(little animated guys standing on two legs) are scaled in the Y axis using a Gaussian distribution. The walk pattern that they have is also randomized to the left and right a little bit. The trees and rocks are just randomly generated within the bounds of the terrain itself. There is a problem with that which I have not fixed yet, which is that they spawn inside of the rocks and other things too.

What made me go above and beyond on this project, was that I turned it into a small game. I added a first person controller from Unity, and gave the player a basic shoot/reload sequence.

For the shooting I used ray casts. Each dinosaur has 3 hit points, and on the third hit they are destroyed. To play the animation of the small explosion going off, I used the RaycastHit variable’s point property to make a new explosion wherever the raycast hit.

I also did more than I had to when it came to aesthetics. I added in rocks around the border of  the terrain. Because the terrain is generated randomly, and the Z value will always be different, I had to make a small script so that every time the game starts, the transforms of anything with that script on it will be set to the terrains Z value at the X and Y coordinates of that object.

All assets that I imported or used in any way for this project are listed in the documentation file for it on GitHub.

Trigonometry Demo

Trigonometry Demo on GitHub

Trig Demo on YouTube

trig demo screen capThe is a simple little demo that I did for one of my programming classes which shows that I know how to use basic trigonometry in code. There were two main goals for this project.

  1. Have the hand on the clock follow the mouse cursor through code.
  2. Have the numbers of the clock be generated through code as well.

To have the mouse follow the cursor hand I used the following code:

void RotateToMouse()
// Gets the mouse location from the screen
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Use the Mathf.Atan2 function to get the angle at which we need to rotate
float angleFromCenter = Mathf.Atan2(mouseWorldPos.y, mouseWorldPos.x);

// Since the angle input from Atan2 is returned in radians, we have to
// convert it to degrees in order to use the Quaternion.Euler method.
float degrees = angleFromCenter * Mathf.Rad2Deg + 180;

transform.rotation = Quaternion.Euler(0, 0, degrees);

As you can see from the YouTube video, both of my goals were achieved. How I generated the angle interval for between the numbers is like so:

angleInterval = (-1) Mathf.PI / ((numberOfObjects) / 2);

The reason that I multiplied by -1 in order to get the numbers to go in a clockwise direction when instantiating them, instead of a counter-clockwise direction.

I also have a float called startAngle, which is (PI/2), so that the generation starts at the top like a clock would. Obviously this is adjustable through the code.