How Can I Order The Scores List By Newest Added? Unity C#


I have 5 scripts to make the scoreboard. But I don’t know how to order the list (the scores which are stores in a list) by newest added. Can someone please help me? Thanks 🙂

First Script:

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

public class RowUi : MonoBehaviour
{
    public TextMeshProUGUI score;
}

Second Script:

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

public class ScoreManager : MonoBehaviour
{
    private ScoreData sd;

    private void Awake()
    {
        var json = PlayerPrefs.GetString("scores", "{}");
        sd = JsonUtility.FromJson<ScoreData>(json);
    }

    public IEnumerable<Score> GetHighScore()
    {
        // **THIS IS WHERE THE SCORE IS ORDERD BY DESCENDING** //
        return sd.scores.OrderByDescending(x => x.score);
    }

    public void AddScore(Score score)
    {
        sd.scores.Add(score);
    }

    private void OnDestroy()
    {
        SaveScore();
    }

    public void SaveScore()
    {
        var json = JsonUtility.ToJson(sd);
        PlayerPrefs.SetString("scores", json);
    }
}

Third Script:

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

public class ScoreUi : MonoBehaviour
{
    public static ScoreUi instance;

    public RowUi rowUi;
    public ScoreManager scoreManager;

    private void Start()
    {
        instance = this;

        if(gameObject.activeInHierarchy == true)
        {
            ScoreUi.instance.AddScoreToBoard();
        }

        var scores = scoreManager.GetHighScore().ToArray();
        for(int i = 0; i < scores.Length; i++)
        {
            var row = Instantiate(rowUi, transform).GetComponent<RowUi>();
            row.score.text = scores[i].score.ToString();
        }
    }

    public void AddScoreToBoard()
    {
        scoreManager.AddScore(new Score(UserInput.instance.score));
    }
}

Fourth Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class ScoreData
{
    public List<Score> scores;

    public ScoreData()
    {
        scores = new List<Score>();
    }
}

Fifth Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class Score
{
    public int score;

    public Score(int score)
    {
        this.score = score;
    }
}

I hope I explained this well enough and if you need extra info, just tell me 🙂



Source link

More To Explore

Share on facebook
Share on twitter
Share on linkedin
Share on email