Unity exporting only one value to json?

I’m making a Unity Game with TikTokLive Unity library, it’s my first time using Dictionaries and Jsons in Unity so I might be doing something very wrong… The whole code I will be sending below is included in the GiftRow class.

This is the initialization of the dictionary

public class GiftRow : MonoBehaviour
{
        private Dictionary<string, int> usersCoinsTotal = new Dictionary<string, int>();
        private void Awake()
        {
            LoadFromFile();

        }

Here is the Init function that is called somewhere else when someone gifts

public void Init(TikTokGift gift)
{
    OnGiftUpdateCoins(gift.Sender.UniqueId, GetGiftValue(gift.Gift.Name));
    Gift = gift;
    Gift.OnAmountChanged += AmountChanged;
    Gift.OnStreakFinished += StreakFinished;
    txtUserName.text = $"{Gift.Sender.UniqueId} sent a {Gift.Gift.Name}!";
    txtAmount.text = $"{Gift.Amount}x";
    RequestImage(imgUserProfile, Gift.Sender.AvatarThumbnail);
    RequestImage(imgGiftIcon, Gift.Gift.Image);
    // Run Streak-End for non-streakable gifts
    if (gift.StreakFinished)
        StreakFinished(gift, gift.Amount);
}

OnGiftUpdateCoins and GetGiftValue functions

private void OnGiftUpdateCoins(string username, int coins)
{
    if (usersCoinsTotal.ContainsKey(username))
    {
        usersCoinsTotal[username] += coins;
        Debug.Log($"{username}'s coin value updated to: {usersCoinsTotal[username]}\n");
    }
    else
    {
        usersCoinsTotal.Add(username, coins);
        Debug.Log($"{username}'s coin value created as: {coins}\n");
    }
    ExportSaveObjectsToJson();
}

public int GetGiftValue(string giftName)
{
    if (giftValues.ContainsKey(giftName))
    {
        return giftValues[giftName]; // Return the coin value if the gift exists
    }
    else
    {
        Debug.LogWarning("Gift not found: " + giftName); // Log a warning if the gift is not in the dictionary
        return 0; // Return 0 if the gift doesn't exist
    }
}

ExportSaveObjectsToJson function

public void ExportSaveObjectsToJson()
{
    // Convert the list of SaveObject to JSON string
    string jsonString = JsonConvert.SerializeObject(usersCoinsTotal, Formatting.Indented);

    // Define the path to save the JSON file
    //string path = Application.persistentDataPath + "/saveObjects.json";
    string path = "D:/saveObjects.json";

    // Write the JSON to the file
    File.WriteAllText(path, jsonString);

    Debug.Log("Save objects exported to JSON file at: " + path);
}

Also json doesnt save every time I close the game, for which I created this function

private void OnApplicationQuit()
{
    Debug.Log("Game quit");
    //foreach (var i in usersCoinsTotal.Values)
    //{
    //    Debug.Log(i);
    //}
    ExportSaveObjectsToJson();
    foreach (var kvp in usersCoinsTotal)
    {
        Debug.Log($"{kvp.Key}: {kvp.Value}");
    }
}

Thanks for reading this far :slight_smile:

Issue is when I run the game, it connects to the stream successfully and the game shows all the gifts, however when I close the game, there is only one value in the dictionary (last gifter, username and coins he sent, not total coins added up, but just last gift amount of coins), same is in the json, just one gifter is shown.

Here is the whole json file, this is the last gifter before I closed the game:

{
  "девочка1234590": 1
}

I tried leaving the initialization of dictionary in class and create like ‘new’ dictionary in start and Awake functions, in that case no gifts get saved, it just doesn’t work at all in that case. I want the code to basically save the username and if the username isn’t already inside of the dictionary create a new key and value for it. If it however is there, then just update the existing value for that username.

C#

private void Awake()
{
    LoadFromFile();
}

private void LoadFromFile()
{
    string path = Application.persistentDataPath + "/saveObjects.json"; // Use Application.persistentDataPath

    if (File.Exists(path))
    {
        string jsonString = File.ReadAllText(path);
        try
        {
            usersCoinsTotal = JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonString);
        }
        catch (Exception e)
        {
            Debug.LogError("Error loading save data: " + e.Message);
            usersCoinsTotal = new Dictionary<string, int>(); // Initialize empty dictionary if loading fails
        }
    }
    else
    {
        usersCoinsTotal = new Dictionary<string, int>(); // Initialize empty dictionary if file doesn't exist
    }
}

Update Coins on Gift:

  • In OnGiftUpdateCoins() , accumulate the total coins for each user:

C#

private void OnGiftUpdateCoins(string username, int coins)
{
    if (usersCoinsTotal.ContainsKey(username))
    {
        usersCoinsTotal[username] += coins;
    }
    else
    {
        usersCoinsTotal.Add(username, coins);
    }
    ExportSaveObjectsToJson(); // Save after each update
}

Save on Quit:

  • In OnApplicationQuit() , simply call ExportSaveObjectsToJson() to save the updated dictionary:

C#

private void OnApplicationQuit()
{
    ExportSaveObjectsToJson();
}