Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to save and display score from and to database?

Discussion in 'Scripting' started by SamVorst, Dec 19, 2019.

  1. SamVorst

    SamVorst

    Joined:
    Nov 28, 2019
    Posts:
    63
    Hi,

    I use a database, mongoDB and i have followed a tutorial how to setup etc.
    But he doesn't tell how to go further, like displaying it and save it to the cloud. Does someone know this?

    Thanks Sam

    This is my script:

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Networking;
    6. using System.Linq;
    7.  
    8. public class networker : MonoBehaviour {
    9.     private string apiKey = "API";
    10.     private string mlabUrl = "Link";
    11.     public Score[] scores;
    12.  
    13.     [System.Serializable]
    14.     public class Score {
    15.         public int score;
    16.         public string name, date, deviceID;
    17.     }
    18.  
    19.     public IEnumerator UpdateHighScore(int newHighScore) {
    20.         string request = mlabUrl
    21.             + "?&q={\"deviceID\":\"" + SystemInfo.deviceUniqueIdentifier + "\"}"
    22.             + "&m=true&u=true&apiKey=" + apiKey;
    23.  
    24.         Score scoreData = new Score();
    25.         scoreData.score = newHighScore;
    26.         scoreData.name = PlayerPrefs.GetString("playerName", "defaultname");
    27.         scoreData.date = System.DateTime.Now.ToString();
    28.         scoreData.deviceID = SystemInfo.deviceUniqueIdentifier;
    29.  
    30.         string json = JsonUtility.ToJson(scoreData);
    31.         json = "{ \"$set\" : " + json + "}";
    32.         var scoreBytes = System.Text.Encoding.UTF8.GetBytes(json);
    33.  
    34.         UnityWebRequest www = UnityWebRequest.Put(request, scoreBytes);
    35.         www.SetRequestHeader ("content-type", "application/json");
    36.         yield return www.SendWebRequest();
    37.  
    38.         if (www.isNetworkError || www.isHttpError) {
    39.             Debug.Log(www.error);
    40.         } else {
    41.             Debug.Log("New high score set to " + newHighScore.ToString());
    42.         }
    43.     }
    44.        
    45.     [System.Serializable]
    46.     private class Wrapper<T>
    47.     {
    48.         public T[] array;
    49.     }
    50.  
    51.     public IEnumerator GetScores() {
    52.         UnityWebRequest www = UnityWebRequest.Get(mlabUrl + "?&apiKey=" + apiKey);
    53.         yield return www.SendWebRequest();
    54.  
    55.         if(www.isNetworkError || www.isHttpError) {
    56.             Debug.Log(www.error);
    57.         }
    58.         else {
    59.             string json = "{ \"array\": " + www.downloadHandler.text + "}";
    60.             Wrapper<Score> wrapper = JsonUtility.FromJson<Wrapper<Score>> (json);
    61.             scores = wrapper.array.OrderByDescending(go => go.score).ToArray();
    62.         }
    63.     }
    64.  
    65.     public static networker instance;
    66.  
    67.     void Awake() {
    68.         if (instance == null)
    69.             instance = this;
    70.     }
    71. }
     
  2. MWizard

    MWizard

    Joined:
    Jan 5, 2017
    Posts:
    78
    Generally speaking, connecting to a database requires authentication of some type. Not sure if this database is local to each game instance (which is not going to work for a high scores database), or setup on a host somewhere remotely (this is necessary for a high scores database), but I only see web requests in your code.

    Ultimately, what you have to do is...

    1. Setup a connection from client to "server"
    2. "server" will communicate with your hosted high scores DB directly (and securely) and update DB data
    3. "server" will send the data back to the client, and the client takes the data and displays it
    I hope this leads you in the right direction. I have been working at understanding networking in game design for a couple of years now, and I'm having quite a few issues with even sending basic text/number data from server to client. Without that, you can't securely update a central DB with highscores and the like.

    If you are making a WebGL game and embedding it in a php page, you can do all of the server connectivity to the database securely, but having the game communicate with a php page that acts as your "server" would be up to you to figure out with the mongoDB tutorials.

    Hope this helps. :)
     
  3. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    I see serializing going on in there as well as players refs, and you want to connect to a database?

    You want to use a php form to post to the database.

    unless you’re calling the serialized file a dB.
     
  4. JeffDUnity3D

    JeffDUnity3D

    Unity Technologies

    Joined:
    May 2, 2017
    Posts:
    14,446
    You should never create db connections directly from the client, your database will not scale and is not secure. Instead, user a proper REST Web Service API, or similar.
     
  5. SamVorst

    SamVorst

    Joined:
    Nov 28, 2019
    Posts:
    63
    Hi, thanks all! I use a Api, I maked it invisible. I will take a look at your answers!

    private string apiKey = "API";
    private string mlabUrl = "Link";
     
  6. JeffDUnity3D

    JeffDUnity3D

    Unity Technologies

    Joined:
    May 2, 2017
    Posts:
    14,446
    Can you elaborate, what do you mean by invisible? A REST API typically has an http or https endpoint to a web server. The web server in turn talks to the database over a single secure connection, then forwards along the information to the client.
     
  7. SamVorst

    SamVorst

    Joined:
    Nov 28, 2019
    Posts:
    63
    I deleted it from this script because there is important data on it... It has an https!
     
  8. JeffDUnity3D

    JeffDUnity3D

    Unity Technologies

    Joined:
    May 2, 2017
    Posts:
    14,446
    So you've created a REST API?
     
  9. SamVorst

    SamVorst

    Joined:
    Nov 28, 2019
    Posts:
    63
    I guess ...