Unity Firebase Realtime Database | Unity Tutorial
In this video tutorial, we’ll explore how to integrate Firebase Realtime Database with Unity, step-by-step! You'll learn how to set up your Firebase project, connect it to your Unity game, and write scripts to read and write data in real-time.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
3 Unity Projects Only $50 - ON SALE!!!!
Contact: unitycoderz2022@gmail.com
=========================================================
Script:
RealtimeDatabase.cs
using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Extensions;
public class RealtimeDatabase : MonoBehaviour
{
private DatabaseReference databaseReference;
[Header("User Data")]
public string username;
public int coins;
public int highestScore;
void Start()
{
// Initialize Firebase
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted)
{
Debug.LogError("Failed to initialize Firebase: " + task.Exception);
return;
}
FirebaseApp app = FirebaseApp.DefaultInstance;
databaseReference = FirebaseDatabase.DefaultInstance.RootReference;
Debug.Log("Firebase Initialized");
// Load initial data if necessary
LoadData("user123"); // Replace with actual user ID
});
}
// Save user data
public void SaveData(string userId)
{
UserData userData = new UserData(username, coins, highestScore);
string json = JsonUtility.ToJson(userData);
databaseReference.Child("users").Child(userId).SetRawJsonValueAsync(json).ContinueWithOnMainThread(task => {
if (task.IsFaulted)
{
Debug.LogError("Error saving data: " + task.Exception);
}
else
{
Debug.Log("User data saved successfully");
}
});
}
// Load user data
public void LoadData(string userId)
{
databaseReference.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted)
{
Debug.LogError("Error loading data: " + task.Exception);
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
if (snapshot.Exists)
{
UserData userData = JsonUtility.FromJson<UserData>(snapshot.GetRawJsonValue());
username = userData.username;
coins = userData.coins;
highestScore = userData.highestScore;
Debug.Log($"Loaded Username: {username}, Coins: {coins}, Highest Score: {highestScore}");
}
else
{
Debug.Log("No data found for this user.");
}
}
});
}
// User data structure
[System.Serializable]
public class UserData
{
public string username;
public int coins;
public int highestScore;
public UserData(string username, int coins, int highestScore)
{
this.username = username;
this.coins = coins;
this.highestScore = highestScore;
}
}
}