I'm experiencing a puzzling issue with loading player statistics in my Unity application using Firebase Realtime Database. The problem is that the JSON snapshot sometimes contains an empty string for the userRegistrationDate field, even though it was manually set in the Firebase console. This behavior appears randomly—on some app launches the data loads correctly, while on others it does not.
Description of the Problem
When the app starts, I load the player statistics from Firebase. The userRegistrationDate is set manually by now (since related code not implemented yet) via the Firebase web interface. On some app launches, the JSON returned from Firebase includes the correct date, but on other occasions, it returns an empty string (""). Here are two sample logs from consecutive launches:
Launch 1 (Works - userRegistrationDate is set):
LoadPlayerDataInPlayerInfoSO > gameDataSnapshot [PlayerStats]: GetRawJsonValue() -> {"levelsPlayed":3,"medalsBronze":3,"medalsDiamond":3,"medalsGold":3,"medalsSilver":3,"steeringMovements":2309,"userLastLogin":"2025-03-24T11:59:40.4904775+01:00","userRegistrationDate":"2025-03-22T16:40:52.3537146+01:00"}
Launch 2 (Issue):
LoadPlayerDataInPlayerInfoSO > gameDataSnapshot [PlayerStats]: GetRawJsonValue() -> {"levelsPlayed":3,"medalsBronze":3,"medalsDiamond":3,"medalsGold":3,"medalsSilver":3,"steeringMovements":2309,"userLastLogin":"2025-03-24T11:59:08.5589978+01:00","userRegistrationDate":""}
This is my ExtractPlayerStats Method:
private void ExtractPlayerStats(DataSnapshot playerStatsSnapshot)
{
if (!playerStatsSnapshot.Exists) return;
string jsonData = playerStatsSnapshot.GetRawJsonValue();
if (!string.IsNullOrEmpty(jsonData))
{
if (debugAdditional) Debug.Log($"LoadPlayerDataInPlayerInfoSO > gameDataSnapshot [{playerStatsSnapshot.Reference.Key}]: GetRawJsonValue() -> " + jsonData);
PlayerStats stats = JsonUtility.FromJson<PlayerStats>(jsonData);
if (stats != null)
{
playerInfoSO.AddPlayerStatsJUSTforLoadingWithoutOnPlayerStatsChanged(stats);
}
}
else
{
Debug.LogWarning("PlayerStats JSON data is null or empty.");
}
}
PlayerStats Class (Relevant Parts):
[System.Serializable]
public class PlayerStats
{
[SerializeField] private string userRegistrationDate;
[SerializeField] private string userLastLogin;
// Other fields
[SerializeField] private int levelsPlayed;
[SerializeField] private int medalsBronze;
[SerializeField] private int medalsSilver;
[SerializeField] private int medalsGold;
[SerializeField] private int medalsDiamond;
[SerializeField] private int steeringMovements;
private Timer saveTimer;
private const double SaveDelay = 1000; // 1 second delay before saving
public event Action OnStatsChanged;
public PlayerStats()
{
saveTimer = new Timer(SaveDelay);
saveTimer.AutoReset = false;
saveTimer.Elapsed += OnTimerElapsed;
}
private void TriggerSave()
{
saveTimer.Stop();
saveTimer.Start();
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
OnStatsChanged?.Invoke();
}
public DateTime UserRegistrationDateDatetime
{
get
{
if (DateTime.TryParse(userRegistrationDate, null, System.Globalization.DateTimeStyles.RoundtripKind, out DateTime parsedDate))
{
return parsedDate;
}
else
{
Debug.LogWarning($"Invalid date format for userRegistrationDate: >{userRegistrationDate}<");
return DateTime.MinValue;
}
}
set
{
Debug.LogWarning($"Reg Date set <<<<<<<<<<<<<<<<<<<<<<<");
userRegistrationDate = value.ToString("o");
TriggerSave();
}
}
public DateTime UserLastLoginDatetime
{
get
{
if (DateTime.TryParse(userLastLogin, null, System.Globalization.DateTimeStyles.RoundtripKind, out DateTime parsedDate))
{
return parsedDate;
}
else
{
Debug.LogWarning($"Invalid date format for userLastLogin: >{userLastLogin}<");
return DateTime.MinValue;
}
}
set
{
Debug.LogWarning($"Login Date set <<<<<<<<<<<<<<<<<<<<<<<");
userLastLogin = value.ToString("o");
TriggerSave();
}
}
// Other properties...
}
UpdatePlayerStatsAsync Method Hint: I currently commented out the actual save in the database in order to exclude any issues here. Since this did not change anything, the problem (as already assumed) lies somewhere at the loading mechanism / the firebase interaction.
public async Task UpdatePlayerStatsAsync()
{
try
{
string path_playerStats = $"players/{playerInfoSO.PlayerDBUserId}/PlayerStats";
string json = JsonUtility.ToJson(playerInfoSO.PlayerStats);
if (debugImportant)
Debug.Log($"UpdatePlayerStatsAsync > dbReference: {dbReference.ToString() + path_playerStats + json}");
// The database update is commented out for testing:
// await dbReference.Child(path_playerStats).SetRawJsonValueAsync(json);
if (debugImportant) Debug.Log("UpdatePlayerStatsAsync > Stats updated successfully.");
}
catch (Exception ex)
{
Debug.LogError($"Error saving PlayerStats: {ex.Message}");
}
}
Debug Log Summary
- When the app starts, the player data is loaded from Firebase.
- Initially, the userRegistrationDate is set manually in Firebase.
- On several launches, the data loads as expected.
- However, after 5-6 app restarts, I observe the following log output indicating the issue (Hint: The "01.01.0001 00:00:00" is just a default value which is set when the actual string is emtpy ""):
PlayerInfoSO > DebugOut (called from FirebaseDatabaseService > LOAD-PlayerDataInPlayerInfoSO) ... playerStats.UserLastLoginDatetime: 24.03.2025 11:59:08 playerStats.UserRegistrationDateDatetime: 01.01.0001 00:00:00 ...
Invalid date format for userRegistrationDate: ><
Thoughts and observations
- As mentioned, I commented out the saving code (UpdatePlayerStatsAsync), so no writes occur after loading. The issue still happens sporadically, implying that the problem lies in the loading/firebase interaction process.
- What is curious is, that this only happens with the UserRegistrationDateDatetime field and this is the only one which I set manually so far - since I did not implement the relevant code yet.
Has anyone encountered a similar issue where a field that was manually set in the Firebase console intermittently loads as an empty string? Could this be related to Firebase's caching/synchronization mechanisms or a race condition during the initial data load?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744250396a4565139.html
评论列表(0条)