How to dynamically create object using JSON data from REST API in Unity 3D

Over the years Unity has become all very powerful and not just easy. With it's easy to use interface and handy programming language C# it is one of the best possible IDE out there to make applications and not just games.

With the help of SimpleJSON and Unity Networking class you'll see how easy it is to handle web requests in Unity.

So today we are going to fetch and display data from REST API request. By displaying data I don't just mean showing the raw output of JSON but making the objects out of the response data which could be further used as per your requirement.

Let's get started.

First you need to make an API which will return some set of data. For example returning a user's friend list data will contain name, age, joining date of all their friends.
For creating an API you may follow my NodeJS tutorial

Once you have some API let's create a simple Unity application that will make a web request on Button click.
Go to a scene in Unity > Right click in the hierarchy and create a UI > Button.

Leave this be for now and let's create a script that will carry the function of this button.

In you 'Assets' folder create a new folder by the name 'Scripts' for keeping all our scripts.
Inside this folder right click and Create > C# script. Let's name this filer 'API.cs'

Inside API.cs create a method of a name of your choice which will start a coroutine upon call.

public void OnClickSendReq()

Now before we define this coroutine we first need to add support for Unity Networking.
Add 'using UnityEngine.Networking; in the beginning of the script.

Now we define our coroutine.
 IEnumerator UpdateReferredUsersList(string userId)
        WWWForm form = new WWWForm();
        form.AddField("username", userId);

        using (UnityWebRequest www = UnityWebRequest.Post(APIURL, form))
yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError)

This coroutine requires creates a web form using WWWForm and adds a form field 'username' with a value that is passed using the variable userId.

  WWWForm form = new WWWForm();
        form.AddField("username", userId);  

Then using UnityWebRequest we make a Post request on APIURL with the form.
  using (UnityWebRequest www = UnityWebRequest.Post(APIURL, form))

Then the response is handled in the next step.
Now we need to create Unity Game Objects using the data response from the API call. For that we first need to handle the data that is coming. In my case the response data is in JSON. 
To handle JSON data we'll be using a SimpleJSON. It is recommended to get it from the official website but in case you find it uncomfortable you may use a copy I uploaded to Github.

Now create a folder by the name 'Plugins' inside the 'Assets' folder and paste SimpleJSON file in there.

Now go back to editing API.cs and add 
  using SimpleJSON;
to the beginning.

Now in order to handle/parse the JSON data coming from our API response we need to create a Request object.
For this we'll be making a custom class. Add the following code to the extreme bottom of API.cs

public class RequestStatus
    public string status;
    public string msg;

    public static RequestStatus CreateFromJSON(string jsonString)
        return JsonUtility.FromJson<RequestStatus>(jsonString);



Now back to our coroutine inside the else block web request error checking add 

                int i = 0;
                while (i >= 0)
                    string userExists= JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value;

                    if (
userExists  != "")
                        i = -1;

This block of code will loop through all the data under 'data'  you might have to modify 
according to the response of you API.

Now to create objects using the response data we called a method with the values of individual set of data.
In this method ListUserData we will instantiate a prefab that will hold the data of individual set.

Create a new method within the else block

                void ListUserData(string username, string email)
                    Debug.Log("Listing users data by instantiating prefab!");
                    GameObject listingObject= Instantiate(userlistPrefab, userlistContainer);
                    UserListing userListing= 
                    userListing.PopulateUserData(username, email);


Now this method will instantiate a prefab 'userlistPrefab' as a child object of 'userlistContainer'. 
We don't just want to instantiate an object but want the data to be displayed on this object. For this we will create a new class 'UserListing' which defines the listing object structure and will have a method 'PopulateUserData' for updating the values of the object.

Head back to Unity and inside Assets > Scripts > Create a new C# script UserListing.

Now inside UserListing 

using UnityEngine.UI;
public class UserListing : MonoBehaviour
    [SerializeField]  private Text username;
private string email;

public void PopulateUserData(string usernameInput, string emailInput)
        username.text = usernameInput;
        email = emailInput;

Now let's create our userListingPrefab to which UserListing class will be applied to.
To create a prefab head back to the scene in Unity and create an Empty GameObject 'UserScrollRect' inside the Panel.
There must a Panel under the Canvas already if you created a button in the very beginning of this tutorial.
If it is not there create a button now and redo the above step.
In the Inspector tab of UsersScrollRect click Add Component and add a Scroll Rect(script).
Uncheck Horizontal.

Now create a child object to UsersScrollRect by the name UserDataContainer which will hold all the prefab object we'll create next. Stretch and set position UserScrollRect according to your need. 
Add Vertical Layout Group (Script) to UserDataContainer.

Under UserDataContainer create a child object, preferably a UI > Image
Stretch it according to your need and Add a UI > Text Object to it. This will be carrying the username from the script.
Add UserListing script to UserListing Object.

Drag and drop Username text object in the blank field against Username in the script properties. In my case it says Name Text as this screenshot was taken later. So I hope this will not confuse anyone.

Once added drag and drop the UserListing object from Hierarchy to Prefabs folder in Project tab.

Create a new Empty Game Object, let's name it 'WWW' and attach API.cs we created above.
    [SerializeField] private GameObject userListingPrefab;
    [SerializeField] private GameObject UserInformationPanel;

to API.cs and drag and attach the prefab we created.
For the UserInformationPanel game object we have to add UserDataContainer we created above.

Open the inspector tab of our button and add  OnClickSendReq to be executed on click.

You might have to set up the objects hierarchy according to your need. I'll leave that to you.

Feel free to leave a comment if you need any help with this.

Next Post Previous Post
No Comment
Add Comment
comment url