How to Connect to an API in Unity 3D

Prasanth
3 min readJan 18, 2020

--

While developing a game or an application in Unity 3D, Most of the time we need to connect our application with back-end using API (Application Programming Interface). So now we are going to see how can we easily connect out Unity application with API. Before that you can visit my following GitHub repository to get the sample project which i going to explain you now as a reference.

https://github.com/prasanthse/Unity-3D-API-Integration.git

First i am going to create a method as IEnumerator and pass two parameters into it. The first one is a string variable, and the other one is an Action<string> delegate type.

I use IEnumerator because i am going to call the method within StartCoroutine. The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed.

I am going pass my API URL for the first parameter and for the Action delegate type going to pass a method.

DownloadHandler objects are helper objects. I attached this object with UnityWebRequest (UnityWebRequest object is used to communicate with web servers). they define how to handle HTTP response body data received from a remote server. Here I used it to buffer response body. After that Yielding the WebRequestAsyncOperation inside a coroutine will cause the coroutine to pause until the UnityWebRequest encounters a system error or finishes communicating. Then I checked for any HTTP / network errors and finally return the response for the method which i pass as the parameter as a delegate type.

This Above LoadJsonCallBack is the method which i use to pass as the parameter inside the GetRequest method. Here in this method first i check whether the response is null or not and if it is not null then create an object from it’s Json representation. After that do what ever you want from this object.

If you need a small data structure that holds a data that you wont modify later, structs are the best
If you need a small data structure that holds a data that you wont modify later, structs are the best

Note: Make sure that your back-end variable names and the variable names that you use in your Json object in the Unity script is exactly the same. Otherwise you will get null value for the variable which you mentioned incorrectly.

Finally i create a method to call the GetRequest method.

As overall this is how my script is looks like,

This is the end of my blog. So If you enjoyed this blog post, share it with your friends and give your feedback.

Thank you!

--

--

Prasanth
Prasanth

Written by Prasanth

Senior Software Engineer | Game Developer

Responses (1)