How to save and display score from and to database?

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:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Linq;

public class networker : MonoBehaviour {
    private string apiKey = "API";
    private string mlabUrl = "Link";
    public Score[] scores;

    [System.Serializable]
    public class Score {
        public int score;
        public string name, date, deviceID;
    }

    public IEnumerator UpdateHighScore(int newHighScore) {
        string request = mlabUrl
            + "?&q={\"deviceID\":\"" + SystemInfo.deviceUniqueIdentifier + "\"}"
            + "&m=true&u=true&apiKey=" + apiKey;

        Score scoreData = new Score();
        scoreData.score = newHighScore;
        scoreData.name = PlayerPrefs.GetString("playerName", "defaultname");
        scoreData.date = System.DateTime.Now.ToString();
        scoreData.deviceID = SystemInfo.deviceUniqueIdentifier;

        string json = JsonUtility.ToJson(scoreData);
        json = "{ \"$set\" : " + json + "}";
        var scoreBytes = System.Text.Encoding.UTF8.GetBytes(json);

        UnityWebRequest www = UnityWebRequest.Put(request, scoreBytes);
        www.SetRequestHeader ("content-type", "application/json");
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError) {
            Debug.Log(www.error);
        } else {
            Debug.Log("New high score set to " + newHighScore.ToString());
        }
    }
       
    [System.Serializable]
    private class Wrapper<T>
    {
        public T[] array;
    }

    public IEnumerator GetScores() {
        UnityWebRequest www = UnityWebRequest.Get(mlabUrl + "?&apiKey=" + apiKey);
        yield return www.SendWebRequest();

        if(www.isNetworkError || www.isHttpError) {
            Debug.Log(www.error);
        }
        else {
            string json = "{ \"array\": " + www.downloadHandler.text + "}";
            Wrapper<Score> wrapper = JsonUtility.FromJson<Wrapper<Score>> (json);
            scores = wrapper.array.OrderByDescending(go => go.score).ToArray();
        }
    }

    public static networker instance;

    void Awake() {
        if (instance == null)
            instance = this;
    }
}

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…

  • Setup a connection from client to “server”
  • “server” will communicate with your hosted high scores DB directly (and securely) and update DB data
  • “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. :slight_smile:

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.

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.

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";

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.

I deleted it from this script because there is important data on it… It has an https!

So you’ve created a REST API?

I guess …