,

Creating an Online Leaderboard Using Unity with Express JS and MongoDB

Posted by

Creating an online Leaderboard in Unity using Express JS and MongoDB can provide a fun and competitive aspect to your game. In this tutorial, we will guide you through the process of setting up a backend server with Express JS and MongoDB and integrating it with your Unity game to create an online Leaderboard system.

Step 1: Set up MongoDB database

First, you need to have MongoDB installed on your machine. You can download MongoDB from the official website and follow the installation instructions.

Once MongoDB is installed, open a terminal and start the MongoDB server by running the command mongod. This will start the MongoDB server on the default port 27017.

Next, open another terminal and connect to the MongoDB server by running the command mongo. This will open the MongoDB shell where you can create a new database for your Leaderboard system.

To create a new database, run the following command in the MongoDB shell:

use leaderboard

Next, create a collection for storing player scores by running the following command:

db.createCollection("scores")

Step 2: Set up Express JS server

Now, let’s set up the backend server using Express JS. Create a new directory for your server and navigate to it in the terminal.

Initialize a new Node.js project by running the following command:

npm init -y

Next, install Express JS and MongoDB driver for Node.js by running the following commands:

npm install express mongodb

Create a new file named server.js in your project directory and add the following code to set up the Express server:

const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'leaderboard';

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
    if (err) {
        console.error(err);
        return;
    }

    const db = client.db(dbName);

    app.post('/submitScore', (req, res) => {
        const { playerName, score } = req.body;

        db.collection('scores').insertOne({ playerName, score }, (err, result) => {
            if (err) {
                console.error(err);
                res.status(500).send('Error submitting score');
            } else {
                res.status(200).send('Score submitted successfully');
            }
        });
    });

    app.get('/leaderboard', (req, res) => {
        db.collection('scores').find().sort({ score: -1 }).limit(10).toArray((err, results) => {
            if (err) {
                console.error(err);
                res.status(500).send('Error fetching leaderboard');
            } else {
                res.status(200).json(results);
            }
        });
    });

    app.listen(3000, () => {
        console.log('Server running on http://localhost:3000');
    });
});

This code sets up an Express server with the routes /submitScore for submitting player scores and /leaderboard for fetching the top 10 scores.

Step 3: Integrate Express JS server with Unity

In your Unity game, create a new C# script to handle the communication with the Express server. Here’s an example of how you can send player scores to the server:

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class LeaderboardManager : MonoBehaviour
{
    private const string serverUrl = "http://localhost:3000";

    public void SubmitScore(string playerName, int score)
    {
        StartCoroutine(PostScore(playerName, score));
    }

    private IEnumerator PostScore(string playerName, int score)
    {
        WWWForm form = new WWWForm();
        form.AddField("playerName", playerName);
        form.AddField("score", score);

        using (UnityWebRequest www = UnityWebRequest.Post(serverUrl + "/submitScore", form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log("Error submitting score: " + www.error);
            }
            else
            {
                Debug.Log("Score submitted successfully");
            }
        }
    }
}

You can call the SubmitScore() method in your game whenever a player achieves a new high score.

Step 4: Display the Leaderboard in Unity

To display the Leaderboard in your Unity game, you can create a UI panel with a scroll view and populate it with the top 10 scores fetched from the Express server. Here’s an example of how you can fetch and display the leaderboard:

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class LeaderboardUI : MonoBehaviour
{
    public Text leaderboardText;

    void Start()
    {
        StartCoroutine(GetLeaderboard());
    }

    private IEnumerator GetLeaderboard()
    {
        using (UnityWebRequest www = UnityWebRequest.Get(serverUrl + "/leaderboard"))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log("Error fetching leaderboard: " + www.error);
            }
            else
            {
                string json = www.downloadHandler.text;
                ScoreData[] scores = JsonUtility.FromJson<ScoreData[]>(json);

                string leaderboard = "";
                for (int i = 0; i < scores.Length; i++)
                {
                    leaderboard += (i + 1) + ". " + scores[i].playerName + ": " + scores[i].score + "n";
                }

                leaderboardText.text = leaderboard;
            }
        }
    }

    [System.Serializable]
    private class ScoreData
    {
        public string playerName;
        public int score;
    }
}

Attach the LeaderboardUI script to a UI panel in your game and assign the leaderboardText field to a Text component where you want to display the Leaderboard.

That’s it! You have successfully set up an online Leaderboard system in Unity using Express JS and MongoDB. Players can now compete for the top spot on the Leaderboard and compare their scores with others.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@random_precision_software
4 months ago

Just come your channel, I've subbed hoping for more UNITY tutorials