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. Dismiss Notice

Resolved Can't add to a List?

Discussion in 'Scripting' started by MasterDisaster64, Jan 11, 2021.

  1. MasterDisaster64

    MasterDisaster64

    Joined:
    Jun 1, 2019
    Posts:
    5
    I'm trying to make an offline scoreboard for my game. Here's the current code:
    Code (CSharp):
    1. public void addScoreEntry(int score, string name) {
    2.         ScoreEntry newEntry = new ScoreEntry(score, name);
    3.         Debug.Log("New entry: " + newEntry.score + " " + newEntry.name);
    4.  
    5.         scoreEntryList.Add(newEntry);
    6.  
    7.         string json = JsonUtility.ToJson(scoreEntryList);
    8.         PlayerPrefs.SetString("highscoreTable", json);
    9.         PlayerPrefs.Save();
    10.         Debug.Log(PlayerPrefs.GetString("highscoreTable"));
    11.     }
    The sorting hadn't been implemented yet. At first I tried to Insert the entry at the right position, but that didn't work either.
    Anyway, the problem is that when the last Debug.Log is called, the List still seems to be empty, as if the Add never happened. Anyone who can help with this?
    It can't be that the list isn't initialized, because I have this in the Awake() of the same component:
    Code (CSharp):
    1. if (PlayerPrefs.HasKey("highscoreTable")) {
    2.             scoreEntryList = JsonUtility.FromJson<List<ScoreEntry>>(PlayerPrefs.GetString("highscoreTable"));
    3.         }
    4.         else {
    5.             scoreEntryList = new List<ScoreEntry>();
    6.         }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    Stay away from Unity's JSON. It cannot do dictionaries or hashsets and looks from here it cannot do lists either. Not only that but it fails with properties and I can't even remember what else. Just do not use.

    Go to the asset store and get JSON .NET... it's FREE! It's a "Real" JSON, not a "Tiny" JSON
     
    MasterDisaster64 likes this.
  3. MasterDisaster64

    MasterDisaster64

    Joined:
    Jun 1, 2019
    Posts:
    5
    This tutorial seems to do it just fine with the built-in JSON, but I'll try the asset.