Implementing backend for Unity3D games using PHP

Written by kmehant | Published 2018/12/24
Tech Story Tags: php | unity3d | mysql | hackernoon | games

TLDRvia the TL;DR App

Introduction

Unity3D has become one of the popular game engines today. You can develop cross-platform games with just a few changes in the code. If you are very much comfy in using JavaScript or C#, then Unity3D should be your choice.

Gamification

The success behind many games in the industry would surely be the best practices in gamification. Gamification involves everything which makes the game more competitive and drives more adrenaline to hit top positions in the leaderboard. Making a leaderboard for a game is not that easy because there is a good of many components such as database security, userAuth so on …

Implementation

Here we are going to implement a leaderboard using PHP and MySQL for a simple game on unity3D. Here is the plan:

  • Write PHP scripts to do SQL queries on to our database
  • Write C# scripts to send and access data between our application and the backend server. Here our application will be the Unity3D game so we are going to use their own documentation to implement it.
  • Finally dumping our database on to a cloud, though we test it on localhost during development 😃.

What we will implement

We will make this as simple as possible so that we can have a better learning experience. We have a game where we have to store username and score in the database. So whenever the game ends we are going to store those data in the database and then retrieve the whole data which will be sorted and displayed on the leaderboard. Isn’t that simple. Let’s implement it now 😃.

Writing PHP scripts

You need to have some back-end scripting idea😉.

We will be writing two PHP files.

  • _data.php_ For sending and retrieving data
  • update.php For updating the score of the player whenever he makes a local high score.

data.php :

we are going to declare a few essential variables to use in our code.

$servername = "host_name";$dbname = "dabase_name";$username = "username";$password = "database_password";$playername = $_POST["playernamePost"];$score = $_POST["scorePost"];

$playername this variable is used to store the username which is sent from our game application. $_POST["playernamePost"] this is a particular action which says that it is going to get the data stored in the variable playernamePost which is sent by some unknown source. Though this isn’t that secure, we will just look into the basic implementation. The same goes with the $score variable too.

Next, connecting the database

$db = mysqli_connect($servername, $username,$password, $dbname);

once the connection is successful we can go further using the SQL queries to our data.

$sql = " SELECT * FROM data ORDER BY score";$push = "INSERT INTO data ( name, score) VALUES ('".$playername."','".$score."')";

$sql this variable stores the SQL query (data retrieval) in the form of a string. $push this variable stores the SQL query _(_data pushing to the database) in form of a string again. You need to have some idea about the SQL query statements like what does SELECT , INSERT and so on… do to the data. They are very simple to understand though 😜. name and score are the columns of our database table. data is the table name. ORDER BY this is used to sort our data without much hassle to write separate sorting algorithms for our data. I suggest you to avoid using it as it not that efficient.

Making these queries work

$retrieval = mysqli_query($db, $sql);$pushdata = mysqli_query($db,$push);

Sending the variables as arguments to mysqli_query function will complete our job.

You might think how our game application is going to get the data. That’s simple we print all the data as a single string on to our PHP file. Later we will retrieve that data as a single string and do some string handling stuff to put it in our LeaderBoard.

while ($row = mysqli_fetch_assoc($retrieval)){echo";".$row['name'].":".$row['score']."";}

We are going to fetch data using mysqli_fetch_assoc($retrieval)into a single variable $rowand then use a while loop to print the complete data. We are done with data.php

Now we can retrieve and push data using data.php file. Now when you have to update the player’s score when he hits a high score, then you have to use this update.php script. This would be quite similar to data.php you simply use an update query.

update.php

$servername = "host_name";$dbname = "database_name";$username = "username";$password = "password";

$playername = $_POST["playernamePos"];$score =$_POST["scorePos"];$db = mysqli_connect($servername, $username,$password, $dbname);$update = "UPDATE data SET score='$score' WHERE name='$playername'";$result = mysqli_query($db,$update);

You find the particular column with the help of username and then you update the corresponding high score.

We are done with writing PHP files. Now let’s write C# scripts to connect the application and the back-end.

Writing C# scripts in Unity3D

You need to be comfortable with unity3D documentation 😜.

retrieval.cs

public string url = "www.somecloudstorage.com/data.php";IEnumerator Start (){WWW retrieve = new WWW(url);yield return retrieve;string fulldata = retrieve.text;users = fulldata.Split(';');int n =0;list.text = "";for (int i = users.Length-1; i>=0; i--){n++;if (users[i] != "->0" && !(users[i].StartsWith("<"))){items = users[i].Split(':');list.text = list.text+ "\n"+n+". "+ items[0];list2.text = list2.text + "\n" + items[1];}}}

IEnumarator is very useful here, as we want the program execution to pause until our whole data is loaded from the PHP file. We do an HTTP request to that particular PHP file. We do this by creating a WWW object and sending the required URL. Then we will wait until the data is loaded completely. We can access the data as a single string using retrieve.text (check out Unity3D documentation when needed). Rest is quite easy, where we do some string handling stuff to retrieve it in the desired form.

We were able to retrieve data which was a cake walk, right!! Now let’s check out how we are going to push data to the database from our game application.

push_highscore.cs

public string url = "www.somecloudstorage.com/data.php";public void pushData(string username, int highscore){WWWForm form = new WWWForm ();form.AddField("playernamePos",username); form.AddField("scorePos",highscore);WWW push_Data = new WWW(url,form);}

This few lines of PHP code would complete our job. ⭐️ Remember that we are using Unit3D official documentation to implement this so you have to import the necessary packages.

Almost everything is done!! But I won't talk about how you will be updating the score. Have fun implementing it by yourself and I am sure you will be able to 😜.

Dumping your data into a cloud space is obviously essential. You may find many cloud space providers in the market and dump your back-end code (PHP files), the database file (.sql file) and properly configure your PHPMyAdmin too. That’s it you are done!! 🎉

Conclusion

That’s it this is the basic way to implement a leaderboard and code your own back-end for your game application using PHP and MySQL 👋.

🌟Remember that this is not at all a secure way of implementing a leaderboard for a game application(production). This is just to make you get up and start. 🌟

You can catch me on @mehant1(Twitter) and https://github.com/kmehant 😃.


Published by HackerNoon on 2018/12/24