Need help with Highscores

Hello,

EDIT: I have find out this, but there’s one last thing - read my last post please.

I am finalizing my game and there’s the last thing I want to add - online highscore ranking with usernames. I want to add an option, where the player can create his username before playing, then his highscore would be stored and published online.

I have writed the highscore thing with this tutorial:

but my game don’t have the username option yet. I don’t know how to add it and connect it to the highscore script. Is there aynone that knows how to make it or can provide links to some tutorials related to that topic?

Here is the script (C#):

“Highscores”:

using UnityEngine;
using System.Collections;

public class HighScores : MonoBehaviour {

    const string privateCode = "here goes the private code";
    const string publicCode = "here goes the public code";
    const string webURL = "http://dreamlo.com/lb/";

    public Highscore[] highscoresList;
    static HighScores instance;
    DisplayHighscores highscoresDisplay;


    void Awake()
    {
        instance = this;
        highscoresDisplay = GetComponent<DisplayHighscores>();
    }


    public static void AddNewHighscore(string username, int score)
    {
        instance.StartCoroutine (instance.UploadNewHighscore (username, score));
    }


    IEnumerator UploadNewHighscore(string username, int score)
    {
        WWW www = new WWW (webURL + privateCode + "/add/" + WWW.EscapeURL (username) + "/" + score);
        yield return www;

        if (string.IsNullOrEmpty (www.error))
        {
            print ("Upload Successful");
            DownloadHighscores();
        }
                else
                {
                    print ("Error Uploading: " + www.error);
                }
    }



    public void DownloadHighscores()
    {
        StartCoroutine ("DownloadHighscoresFromDatabase");
    }




    IEnumerator DownloadHighscoresFromDatabase()
    {
        WWW www = new WWW (webURL + publicCode + "/pipe/");
        yield return www;
     
        if (string.IsNullOrEmpty (www.error))
        {
            FormatHighscores (www.text);
            highscoresDisplay.OnHighscoresDownloaded(highscoresList);
        }
        else
        {
            print ("Error Downloading: " + www.error);
        }
    }

    void FormatHighscores(string textStream)
    {
        string[] entries = textStream.Split (new char[] {'\n'}, System.StringSplitOptions.RemoveEmptyEntries);
        highscoresList = new Highscore[entries.Length];
        for (int i = 0; i <entries.Length; i ++)
        {
            string[] entryInfo = entries[i].Split(new char[] {'|'});
            string username = entryInfo[0];
            int score = int.Parse (entryInfo[1]);
            highscoresList[i] = new Highscore(username,score);
            print (highscoresList[i].username + ": " + highscoresList[i].score);
        }
    }

}

public struct Highscore
{
    public string username;
    public int score;

    public Highscore(string _username, int _score)
    {
        username = _username;
        score = _score;
    }
}

“DisplayHighscores”:

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

public class DisplayHighscores : MonoBehaviour {

    public Text[] highscoreText;
    HighScores highscoreManager;

    // Use this for initialization
    void Start ()
    {
        for (int i =0; i < highscoreText.Length; i ++)
        {
            highscoreText[i].text = i+1 + ". Fetching...";
        }

        highscoreManager = GetComponent<HighScores> ();

        StartCoroutine ("RefreshHighscores");
    }

    public void OnHighscoresDownloaded (Highscore[] highscoreList)
    {
        for (int i =0; i < highscoreText.Length; i ++)
        {
            highscoreText[i].text = i+1 + ". ";
            if (highscoreList.Length > i)
            {
                highscoreText[i].text += highscoreList[i].username + " - " + highscoreList[i].score;
            }
        }
    }

    IEnumerator RefreshHighscores()
    {
        while (true)
        {
            highscoreManager.DownloadHighscores();
            yield return new WaitForSeconds(30);
        }
    }

}

“HighscoreTest”:

using UnityEngine;
using System.Collections;

public class HighscoreTest : MonoBehaviour {
 
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Space))
        {
            int score = Random.Range(0,100);
            string username = "";
            string alphabet = "abcdefghijklmnoprstuwxyz";

            for (int i = 0; i < Random.Range(5,10); i ++)
            {
                username += alphabet[Random.Range(0,alphabet.Length)];
            }

            HighScores.AddNewHighscore(username,score);
        }
    }
}

all the code you posted looks like it handles having an username… I think you “just” need to look at the InputFields in the new UI to get the user to put their name in and then use that rather than the random text string in the test.

http://docs.unity3d.com/Manual/script-InputField.html

1 Like

Thank you, I am looking up for some tutorials on youtube related to Input Fields now.

Hello again,

After some experimenting I have nearly everything I need, but there’s one last thing.

In my game, after losing, I have to input any nickname and click “Save Score”. Then my scores are stored on the dreamlo.com server and I can see all the scores, but in the game after clicking “Save Score”, the highscore list should show up. Instead of that, nothing happens. Scores are saved on dreamlo.com, but I can’t see the list in my game. I think it may be something to do just with GUILayout, something simple, but I don’t know what exactly. Can anyone help me with that?

Here is my script (C#):

using UnityEngine;
using System.Collections.Generic;

public class LeaderBoardSample : MonoBehaviour {
   
    public int totalScore = 0;
    string playerName = "";

    public bool hasLost = false;
   
    enum gameState {
        waiting,
        enterscore,
        leaderboard
    };
   
    gameState gs;
   
   
    // Reference to the dreamloLeaderboard prefab in the scene
   
    dreamloLeaderBoard dl;
    dreamloPromoCode pc;

    void OnTriggerEnter2D() {
        hasLost = true;
    }
   
    void Start ()
    {
        // get the reference here...
        this.dl = dreamloLeaderBoard.GetSceneDreamloLeaderboard();

        // get the other reference here
        this.pc = dreamloPromoCode.GetSceneDreamloPromoCode();

        this.gs = gameState.waiting;
    }
   
    void Update ()
    {
        GetComponent<GUIText> ().text = "Score: " + totalScore;
       
        if (hasLost)
        {
                this.gs = gameState.enterscore;
        }
    }
   
    void OnGUI()
    {
                if (hasLost) {
                        GUILayoutOption[] width200 = new GUILayoutOption[] {GUILayout.Width (200)};
       
                        float width = 400;  // Make this wider to add more columns
                        float height = 200;

                        Rect r = new Rect ((Screen.width / 2) - (width / 2), (Screen.height / 2) - (height), width, height);
                        GUILayout.BeginArea (r, new GUIStyle ("box"));
                        GUILayout.BeginVertical ();
       
                        if (this.gs == gameState.enterscore) {
                                GUILayout.Label ("Total Score: " + this.totalScore.ToString ());
                                GUILayout.BeginHorizontal ();
                                GUILayout.Label ("Your Name: ");
                                this.playerName = GUILayout.TextField (this.playerName, width200);
           
                                if (GUILayout.Button ("Save Score")) {
                                        // add the score...
                                        if (dl.publicCode == "")
                                                Debug.LogError ("You forgot to set the publicCode variable");
                                        if (dl.privateCode == "")
                                                Debug.LogError ("You forgot to set the privateCode variable");

                                        dl.AddScore (this.playerName, totalScore);
               
                                        this.gs = gameState.leaderboard;
                                }

                                if (this.gs == gameState.leaderboard) {
                                        GUILayout.Label ("High Scores:");
                                        List<dreamloLeaderBoard.Score> scoreList = dl.ToListHighToLow ();
               
                                        if (scoreList == null) {
                                                GUILayout.Label ("(loading...)");
                                        } else {
                                                int maxToDisplay = 20;
                                                int count = 0;
                                                foreach (dreamloLeaderBoard.Score currentScore in scoreList) {
                                                        count++;
                                                        GUILayout.BeginHorizontal ();
                                                        GUILayout.Label (currentScore.playerName, width200);
                                                        GUILayout.Label (currentScore.score.ToString (), width200);
                                                        GUILayout.EndHorizontal ();
                       
                                                        if (count >= maxToDisplay)
                                                                break;
                                                }
                                        }
                                }

                                GUILayout.EndHorizontal ();
                        }
       

                        GUILayout.EndArea ();

                        r.y = r.y + r.height + 20;

                        GUILayout.Space (50);

                        GUILayout.EndVertical ();
                }
   
        }
}