Create a simple web application for your game using Strapi.js — Part 3

In this part, we are going to use the API that we built, in a Unity game. Notice that you can use any version of Unity but it is recommended to use newer versions (above 2017) to avoid any unexpected errors or behaviors.

The requirements for this tutorial are these:

  • Unity 2017.x+ (I will be using Unity 2020.1.3f1)
  • RestClient Library, latest version (I will be using v2.6.1)
  • Newtonsoft, latest version (I will be using 12.0.3)

After creating a Unity project, download the latest release of RestClient from GitHub and import the unity package file. And for Newtonsoft, download the latest dll library from here; extract it and drag the Newtonsoft.json.dll to your Assets folder, from folder net20 (if you are using .Net Standard 2.0) or net40 (if you are using .Net 4.x).

Now let's create a script in Unity called RemoteConfig.cs

It will be getting the data for all of our heroes in the Start method.

first I introduce a global variable called url in this class which will be the URL to our api:

and then having the RestClient imported, I create a method called getHeroesData and call it in the Start method. But before that, I have to create classes that contain our hero data properties. In order to do that I have to create fields and arrays that match the JSON, sent by the API.

first I call the URL:

(Note that your server should be running to get the response!)

I observe the JSON carefully and start from the data object inside the heroes object:

it will be something like this in C#:

and next, we will create the HeroObject:

That's it! Now we implement the getHeroesData method. We will be sending a GET request to Strapi and Then get the response in the onResolved callback. If anything unexpected happens and we don’t receive the response, the onRejected callback will be called. So we need to do all the deserializing stuff inside the onResolved callback:

we deserialize the response as a list of Hero object that we created before. and then iterate it and do whatever we want with it. I called this method in the Star method and then attached the whole script to an empty GameObject inside the scene:

and then I played the game and saw the script printing the data from the server in the console:

here is the full RemoteConfig class:

So we successfully created a web application that can be hosted on any servers and created an API to retrieve our data and then received those data with a simple C# script in our game.

I hope you enjoyed this series of tutorials. If it was useful to you let me know. Thank you!

My LinkedIn: www.linkedin.com/in/omidrezaizadi

a passionate game developer with 4+ years of experience in Unity3D

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store