Search Unity

How would one connect a Unity game to a Database to store simple amounts of data?

Discussion in 'Multiplayer' started by JoaoBM, Jan 2, 2019.

  1. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    Hey there.

    As a Project for this university's semester, we were instructed to develop a Unity game and a Companion App for Android.
    Both must connect to a Database and communicate with each other.
    For our Project, I just need to have User Authentication in Unity as well as insert some numbers into the Database so my Companion App can retrieve and use them (amount of items collected in Unity, amount of deaths, etc).

    We were told to use NodeJS and MongoDB as it was easier (?). Now, I worked with both of them a few months ago to develop a website but after doing some research, I have no clue on how to implement a MongoDB and NodeJS server in Unity. Seems like there isn't an easy way to do it since I have a restrict programming knowledge when it comes to the server side.

    I'm getting desperate as the delivery date is getting close.

    Are there any easy-to-implement options so I can retrieve, insert data and have User Authentication in both Unity and Companion App?

    Thank you in advance.

    EDIT: Forgot to mention we don't know PHP. We were only teached HTML and Javascript during the website semester.
     
    Last edited: Jan 2, 2019
    Pagi likes this.
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
  3. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    I forgot to mention we weren't given any bases on PHP. Apologies for not mentioning it on the main post. Will update accordingly.

    Thank you for your reply.
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    Its fine.
    But I suggest to grab SQL with PhP server. PHP is not that hard at all, if you grasp basics.

    In my opinion, it is much harder to build website with NodeJS than PHP.
    However, with NodeJS, you can make nice multiplayer games, with connections based on sockets.

    I assume you are learning HTML5 ? Or just raw HTML and Javascript, without CSS?
     
    matronator likes this.
  5. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,977
    Your going to need to know c# at the very least to dive into unity I am afraid.
     
    Antypodish likes this.
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    Yep, that assuming OP has some basics knowledge, or intention to learn c#. But it will not be 5 min job, juts to be aware, to be on safe side.
     
  7. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    Oh I do know C#. I've been at it for the past months. C# is not the problem. The problem was not knowing PHP but I opted for learning the basics and give it a try following @Antypodish 's advice. Everything looking good so far.

    Thank you!

    I have a new issue that came up today.
    In the Unity game for PC I have 3 food items spread throughout the levels that are exactly the same, only varying on the sprites. The Companion App allows the users to unlock new themes and equip them in the Unity game (PC). Doing this will change those 3 sprites according to the theme chosen by the Player.

    What would be the best way to tell Unity, through MySQL and PHP, if a Player has unlocked or equipped a new theme?

    Thank you in advance.
     
  8. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    DB
    On data base side, you would have players, themes and players related theme table, with.
    Players, if more than one, will store basics information about each player. ID, loging data, etc.

    On themes side, you have theme ID and related theme data.

    One player related theme table, you need column for player ID, column for theme ID. That is simplest form.
    But you can expand by adding other data, including column storing IsThemeActive. Etc.

    PHP
    PHP side will need add, or remove references of player to theme, from player related theme table.
    Alternatively just toggle IsThemeActive cell, for matching player / theme.

    In php you have listener by using GET, to receive player ID following by its data in same request.
    Something like for example
    ?playerID=5&themeID=3&themeActive=1

    If you got only one player, then you can shrink to
    ?themeID=3&themeActive=1

    But for more players, you may also need authentication hash code. That providing, you concerns about something hacking application, and changing ID in Unity application registry.

    Unity
    Either way these request will be sent from Unity.

    That's pretty much minimum what you may need.
     
  9. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    Thank you! Will give a look and update accordingly during the following days. Again, thank you very much!
     
    Antypodish likes this.
  10. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    Here I am again, @Antypodish !
    I've been following this youtube series
    and got everything working. When implementing it on my Project, the login and register system work but not the updating of the queries.

    Here are my scripts:

    Unity - Player.cs

    Code (CSharp):
    1. public void prepareSaveData()
    2.     {
    3.         totalTime = Time.timeSinceLevelLoad;
    4.  
    5.         increaseTotalPlays();
    6.         increaseTotalDeaths();
    7.         DatabaseManager.totalWeight = (int) currentWeight;
    8.         DatabaseManager.totalTime = (int) totalTime;
    9.  
    10.         CallSaveData();
    11.  
    12.         totalTime = 0;
    13.         Debug.Log("button hit");
    14.     }
    15.  
    16.     public void CallSaveData()
    17.     {
    18.         StartCoroutine(SavePlayerData());
    19.         Debug.Log("b");
    20.     }
    21.  
    22.     IEnumerator SavePlayerData()
    23.     {
    24.         Debug.Log("t");
    25.         WWWForm form = new WWWForm();
    26.         form.AddField("name", DatabaseManager.username);
    27.         form.AddField("totalDeaths", 2);
    28.         form.AddField("totalPlays", 1);
    29.         form.AddField("totalWeight", 1);
    30.         form.AddField("totalTime", 2);
    31.  
    32.         WWW www = new WWW("http://localhost/pathofbuddhadatabase/savedata.php", form);
    33.         yield return www;
    34.  
    35.         if (www.text == "0")
    36.         {
    37.             Debug.Log("Game Saved");
    38.         }
    39.         else
    40.         {
    41.             Debug.Log("Save failed. Error #" + www.text);
    42.         }
    43.     }
    Unity - DatabaseManager.cs

    Code (CSharp):
    1. public static string username;
    2.     public static int totalDeaths;
    3.     public static int totalPlays;
    4.     public static int totalWeight;
    5.     public static int totalTime;
    6.  
    7.     public static bool LoggedIn { get { return username != null; } }
    8.  
    9.     public static void LogOut()
    10.     {
    11.         username = null;
    12.     }
    PHP - savedata.php

    Code (PHP):
    1. <?php
    2.  
    3.     $con = mysqli_connect('localhost', 'root', 'root', 'pathofbuddhadatabase');
    4.  
    5.     if(mysqli_errno()) {
    6.         echo "1: Connection to database failed";
    7.         exit();
    8.     }
    9.  
    10.     $username = $_POST["name"];
    11.     $newTotalDeaths = $_POST["totalDeaths"];
    12.     $newTotalWeight = $_POST["totalWeight"];
    13.     $newTotalTime = $_POST["totalTime"];
    14.     $newTotalPlays = $_POST["totalPlays"];
    15.  
    16.     $nameCheckQuery = "SELECT username FROM users WHERE username = '" . $username . "';";
    17.  
    18.     $nameCheck = mysqli_query($con, $nameCheckQuery) or die("2: Name check query failed");
    19.  
    20.     if(mysqli_num_rows($nameCheck) != 1) {
    21.         echo "3: A User with that Username already exists or you aren't registered";
    22.         exit();
    23.     }
    24.  
    25.     /*$updateQuery = "UPDATE users SET totalDeaths = " . $newTotalDeaths . ",
    26.                                      totalWeight = " . $newTotalWeight . ",
    27.                                      totalTime = " . $newTotalTime . ",
    28.                                      totalPlays = " . $newTotalPlays . " WHERE username = '" . $username . "';";*/
    29.  
    30.     $updateQuery = "UPDATE users SET totalDeaths = $newTotalDeaths,
    31.                                     totalWeight = $newTotalWeight,
    32.                                     totalTime = $newTotalTime,
    33.                                     totalPlays = $newTotalPlays WHERE username = $username";
    34.     mysqli_query($con, $updateQuery) or die ("7: Save query failed");
    35.  
    36.     echo "0";
    37. ?>
    I linked the Player.cs' prepareSaveData() to a button and it runs every function but no error or success message is returned nor the MySQL database is updated.

    Any idea what the problem might be?
     
  11. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    Can you try send save request via web browser, to see if yo got php side working correctly?
     
  12. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    When I post "http://localhost/pathofbuddhadatabase/savedata.php" on a browser it prints "3: A User with that Username already exists or you aren't registered" which I believe it isn't enough since you're trying to reach to the bottom of the php code.
    If so, could you give me guidelines on how to perform it?

    Thank you for your time.

    Edit: Ok this is odd. I swear I didn't touch anything but the MySQL just updated. So weird.

    Edit2: The values are being correctly updated in the database but Unity is not printing the success message.
     
    Last edited: Jan 6, 2019
  13. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    You can try create simple php, or even html page, with minimalistic html form, of few inputs and submit button, which sends form as POST.

    Your simple form fields should match your php structure.
    This page would be probably few lines long at most.

    Try and see what you can come up with.
    Alternatively, create copy of your php file, lets say add postfix 2 to file name, and replace POST with GET. Then you call that file via web browser address, with request, using *.php?totalDeaths=3&totalTime=4& etc. Just as an example.
     
  14. JoaoBM

    JoaoBM

    Joined:
    Sep 23, 2018
    Posts:
    15
    I did as you said and everything worked perfectly. I started digging on the Unity Forums and one thread came up saying that it couldn't print a www.text since you were asking for it before the queries and such were done.

    I added some lines of code and everything works now! Thank you!
     
    Antypodish likes this.
  15. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    Well done.
     
    JoaoBM likes this.
  16. PedroHeck

    PedroHeck

    Joined:
    Jan 27, 2019
    Posts:
    11