Вот инициализация пути к файлу и метода запуска:
Код: Выделить всё
private string filePath;
private void Start()
{
filePath = Path.Combine(Application.dataPath, "/userGiftData.json");
//filePath = "C:/Users/Kaki/Desktop/userGiftData.json";
// Check if the file exists, if not, create it
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, "{}");
}
}
Код: Выделить всё
public void Init(TikTokGift gift)
{
if (gift == null || gift.Sender.UniqueId == null || gift.Gift.Name == null)
{
Debug.LogError("Gift or sender data is null!");
return;
}
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);
OnGiftUpdateValue(Gift.Sender.UniqueId, Gift.Gift.Name); //Line 93
}
Код: Выделить всё
public void OnGiftUpdateValue(string userName, string giftName)
{
// Read the existing JSON data from the file
Dictionary userData = ReadUserDataFromJson();
if (giftValues.ContainsKey(giftName))
{
int giftValue = giftValues[giftName]; // Retrieve the value of the gift
// If the user exists in the data, update the total gift value, else create new
if (userData.ContainsKey(userName))
{
userData[userName] += giftValue;
}
else
{
userData[userName] = giftValue; // New user starts with the gift value
}
// Write the updated data back to the JSON file
WriteUserDataToJson(userData); //Line 120
}
else
{
Debug.LogError($"Gift '{giftName}' does not exist in the dictionary.");
}
}
Код: Выделить всё
private Dictionary ReadUserDataFromJson()
{
if (File.Exists(filePath))
{
string jsonData = File.ReadAllText(filePath);
//return JsonConvert.DeserializeObject(jsonData) ?? new Dictionary();
return JsonUtility.FromJson(jsonData);
}
return new Dictionary();
}
private void WriteUserDataToJson(Dictionary data)
{
string jsonData = JsonUtility.ToJson(data);
//File.WriteAllText(filePath, jsonData);
System.IO.File.WriteAllText(filePath, jsonData); //Line 144
Debug.Log("Data saved to: "+filePath);
}
Большое спасибо, что нашли время, чтобы прочитать это!
Подробнее здесь: https://stackoverflow.com/questions/789 ... meter-name