我正在使用 TikTokLive Unity 库制作 Unity 游戏,这是我第一次在 Unity 中使用字典和 Json,所以我可能会做一些非常错误的事情......我将在下面发送的整个代码包含在 GiftRow 类中。
这是字典的初始化
public class GiftRow : MonoBehaviour
{
private Dictionary<string, int> usersCoinsTotal = new Dictionary<string, int>();
private void Awake()
{
LoadFromFile();
}
这是当有人送礼物时在其他地方调用的 Init 函数
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 和 GetGiftValue 函数
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 函数
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);
}
而且每次关闭游戏时 json 都不会保存,为此我创建了这个函数
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}");
}
}
感谢您阅读本文:)
问题是当我运行游戏时,它成功连接到流并且游戏显示所有礼物,但是当我关闭游戏时,字典中只有一个值(最后一个礼物者、用户名和他发送的硬币,而不是总数)硬币加起来,但只是最后赠送的硬币数量),json 中也是如此,只显示一个礼物赠送者。
这是整个json文件,这是我关闭游戏之前的最后一个礼物:
{
"девочка1234590": 1
}
我尝试将字典的初始化留在类中,并在启动和唤醒函数中创建类似“新”的字典,在这种情况下,不会保存任何礼物,在这种情况下它根本不起作用。我希望代码基本上保存用户名,如果用户名不在字典中,则为其创建一个新的键和值。如果存在,则只需更新该用户名的现有值即可。
我实际上修复了这个问题,可能不是我最好的工作,但我创建了一个新字典,可以从每个礼物事件的 json 中加载值。我的意思是,就我的目的而言,这应该没问题,但如果有人有更好的想法,欢迎他们:D