MIF_E31222823/Assets/SCRIPT/ScoreViewer.cs

72 lines
1.8 KiB
C#

using Firebase.Database;
using UnityEngine;
using UnityEngine.UI;
public class ScoreViewer : MonoBehaviour
{
public Text QuizScoreText;
public Text PretestScoreText;
private string userID;
private DatabaseReference dbReference;
private int latestQuizScore = -1;
private int latestPretestScore = -1;
private bool updateUI = false;
void Start()
{
userID = PlayerPrefs.GetString("UserID", "");
if (string.IsNullOrEmpty(userID))
{
Debug.LogError("UserID tidak ditemukan.");
return;
}
dbReference = FirebaseDatabase.DefaultInstance.RootReference;
LoadScores();
}
void Update()
{
if (updateUI)
{
if (latestQuizScore >= 0)
QuizScoreText.text = latestQuizScore.ToString();
if (latestPretestScore >= 0)
PretestScoreText.text = latestPretestScore.ToString();
updateUI = false;
}
}
void LoadScores()
{
dbReference.Child("users").Child(userID).Child("scores").GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted || !task.IsCompleted)
{
Debug.LogError("Gagal mengambil skor: " + task.Exception);
return;
}
DataSnapshot snapshot = task.Result;
if (snapshot.Exists)
{
if (snapshot.Child("quizScore").Exists)
latestQuizScore = int.Parse(snapshot.Child("quizScore").Value.ToString());
if (snapshot.Child("pretestScore").Exists)
latestPretestScore = int.Parse(snapshot.Child("pretestScore").Value.ToString());
updateUI = true;
}
else
{
Debug.Log("Data skor belum tersedia.");
}
});
}
}