How to fetch data from API in Unity

Tutorial on how to fetch data from API for your game in Unity

Benny
Bina Nusantara IT Division

--

Unity Logo from www.unity.com

Have you ever thought of getting data for your game from the internet? Let’s say you have an online game and save the data to the internet and get it back to your game. So you don’t have to save the data to local memory and make your game heavier.
Well, you can easily get data from the internet by using REST API.

What is REST API?

REST (Representational state transfer) and API (Application Programming Interface) is a web service that provides a place for interaction between client and server. This interaction produces a JavaScript object notation or also known as JSON which can be used by many software.

With Unity, using REST API can be really helpful. Not only it will make your games lighter but it can also make it easier for developers to add updated data to their games.

For example, you published a game without a REST API and you want to update enemies status because it’s too strong for the player to defeat the monsters. So you have to manually update your game, rebuild it, and upload it again to the public. it’s really troublesome right?

If you use REST API, all you need to do is to go to your server, update that specific data, save it, and see the magic works.

Getting Started

MockAPI new project

For this tutorial, we’re gonna be using MockAPI to get character status and display them in our game. However, if you have other APIs that you want to use feel free to use it since the process of getting data with REST API is pretty much the same. Just make sure you have the API keys and other keys provided by the API of your choice.

First, you need to create the schema data for your API. We add character status like HP (Healt Point), MP (Magic Point), Attack, Defense, and Agility.

API Schema for Player Status

Create new project in Unity

Let’s create our new project in Unity. On the Projects menu Click “New” button on Unity hub.

Unity Hub Screen

At this point, you can choose template for your games. For now we can use 3D templates. After that you can set your project name and select location of your projects to be saved and click “Create”.

Create new project

Wait for unity to prepare your new projects.

New Unity Project

Create New Script

Now our project is ready and we can create new script for our game. Right click on project window, select “Create” and then select “C# Script”. In this case, I’ll create new folder and name it “Script” and put the new script in there.

Create New Script

First, we create script PlayerStatus.cs for our Model data that will receive data from API. After that, you can open and edit the script with Visual Studio and use the following code :

using System.Collections;using System.Collections.Generic;using UnityEngine;public class PlayerStatus{public string playerName;public int atk;public int def;public int agi;public int hp;public int mp;public string id;}

After that, we create next script GetApiData.cs for get and process the data from API. Use the following code below :

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.Networking;using UnityEngine.UI;public class GetApiData : MonoBehaviour{public string URL;public InputField id;public GameObject playerStatusPanel;
public void GetData(){StartCoroutine(FetchData());}public IEnumerator FetchData(){using (UnityWebRequest request = UnityWebRequest.Get(URL + id.text)){yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.ConnectionError){Debug.Log(request.error);}else{PlayerStatus playerStat = new PlayerStatus();playerStat = JsonUtility.FromJson<PlayerStatus>(request.downloadHandler.text);playerStatusPanel.transform.GetChild(0).GetComponent<Text>().text = playerStat.playerName;playerStatusPanel.transform.GetChild(1).GetComponent<Text>().text = "HP : " + playerStat.hp.ToString();playerStatusPanel.transform.GetChild(2).GetComponent<Text>().text = "MP : " + playerStat.mp.ToString();playerStatusPanel.transform.GetChild(3).GetComponent<Text>().text = "Attack : " + playerStat.atk.ToString();playerStatusPanel.transform.GetChild(4).GetComponent<Text>().text = "Defende : " + playerStat.def.ToString();playerStatusPanel.transform.GetChild(5).GetComponent<Text>().text = "Agility : " + playerStat.agi.ToString();}}}}

I’ll explain the code above step by step. First we create 3 variables :

  • public string URL => A Variable that we use for our API endpoint link.
  • public InputField id => A Variable that we use for ID to get the data. This variable will receive input from user.
  • public GameObject playerStatusPanel => A Variable that we use for control Game Object in the game.

After that, we create 2 functions “public void GetData()” and “public IEnumerator FetchData()”. The GetData() function is going to be used by our UI Button. So whenever you click the button, this funcion will be called. Inside this function, we started a coroutine for our IEnumerator function. Since we can’t just call the IEnumerator function from button click, we had to create GetData() function just to fire the IEnumerator function.

Inside the FetchData() function, we initialized the “UnityWebRequest” and then we send the URL of our API Endpoint for processing the data. Then, we wait for its response and after getting the response we check if it’s a failure or a success. If there is an error we display the error in our console and if it’s a success we create new variable for our Model data that we made earlier, and pass the data from JSON into that model. After that, we can display the data into our Game Object.

Design the game UI

Next thing to do is design our game UI. Let’s make it a simple UI for our game. On the Hierarchy window, right click on some object or click “+” button, select “Game Object”, select “UI”, select “Text”. We will create some text UI, a button, and an input field.

Create an UI Panel

After we create everything we need, the list of objects on hierarchy window will be like this.

Hierarchy window

And the game UI will be like this.

UI design

Setting up our game

Now, our porject is almost done. You have to applied your script to your game. First thing to do is create empty Game Object as a place for our script, we will name it “GameManager”. And we just drag the script GetApiData.cs into that Game Object. After that, the new Game Object we create earlier will have a component of our script.

Inspector of GameManager Object

After that, we want our button to call the GetData() function we create earlier. So, on the button object, we look for “On Click ()” attribute and we click the “+” button. After that we drag the GameManager object from hierarchy into “On Click ()” attribute. Then, we can choose the function that we want to call in this case GetData() function. It will looks like this.

On Click () Attribute for Button

Run your game

We done!! You can run your game by click the play button.

Get Data From API

Conclusion

RESTful API is the best features that make us easier to transfer data between client and server. It can be used by any programming language and any platform. With REST API, you can do more things other than displaying players status. You can send notification to player, chatting system, update item list on NPC shop, and more.

--

--