はじめに
UnityとFirebaseを使ってデータベースの操作をしてみたい
PCスペック
項目 | 情報 |
---|---|
OS | macOS Sonoma 14.4.1 |
ハードウェア | MacBook Pro 16inc 2023 |
プロセッサ | Apple M2 pro |
メモリ | 32GB |
バージョンについて
項目 | バージョン |
---|---|
Unity | 2022.03.22f1 |
firebase_unity_sdk | 12.0.0 |
準備
Firebase Realtime Databaseへのデータの準備
Realtime Databaseのデータタブのページで、白い四角い枠で「+」をクリックしていくと項目が追加出来ます。
そちらで追加して行ってください。
ここのaaa
, bbb
…がuserIdです。
その子要素にhpとatkを入れてあります。
同じ構造で作成してみてください。
firebaseをUnityにimport
FirebaseManeger.csを作成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
using Firebase.Database;
public class FirebaseManager : MonoBehaviour
{
public bool isRead; // データベースを読み込む際はこちらをtrueに. 書き込む際はfalseに
public bool isJson; // データベースにJson形式で書き込む際はここをtrueに
private DatabaseReference _databaseReference;
public string searchTableName = "users";
public string searchUserId = "aaa"; // ここを好きな文字列に変更してみてください
public string newUserId = "ddd"; // ここを好きな文字列に変更してみてください
public int hp = 8; // ここを好きな数値に変更してみてください
public int afterHp = 5; // ここを好きな数値に変更してみてください
public int atk = 18; // ここを好きな数値に変更してみてください
private void Start ()
{
// Set this before calling into the realtime database.
FirebaseDatabase.GetInstance("https://fir-test-8aa4f-default-rtdb.firebaseio.com/");
// Get the root reference location of the database.
_databaseReference = FirebaseDatabase.DefaultInstance.RootReference;
Debug.LogFormat("_databaseReference {0}", _databaseReference);
if (isRead)
{
ReadQuestData(searchUserId);
}
else
{
WriteNewQuestData(newUserId, hp, atk);
}
}
private void WriteNewQuestData(string userId, int hp, int atk)
{
UserData userData = new UserData(hp, atk);
string json = JsonUtility.ToJson (userData);
if (isJson)
{
// データベースにJson形式で書き込む
_databaseReference
.Child(searchTableName)
.Child(userId)
.SetRawJsonValueAsync(json);
}
else
{
// 指定したキーの値を書き換える
_databaseReference
.Child(searchTableName)
.Child(userId)
.Child("hp")
.SetValueAsync(afterHp.ToString ());
}
}
private void ReadQuestData(string userId)
{
FirebaseDatabase.DefaultInstance
.GetReference("users")
.GetValueAsync().ContinueWith(task=>{
if (task.IsFaulted)
{
Debug.LogError("失敗");
}
else if(task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
string json = snapshot.Child(userId.ToString()).GetRawJsonValue();
Debug.Log("Read: "+ json);
}
});
}
}
UserData.csを作成
public class UserData
{
public int hp;
public int atk;
public UserData()
{
}
public UserData(int hp, int atk)
{
this.hp = hp;
this.atk = atk;
}
}
Unity上で必要なオブジェクトを作成
-「Create Empty」を作成
-「FirebaseManager」にリネーム
-FirebaseManager.csをFirebaseManagerにアタッチ
これでOKです。
実行
Firebaseでは現状このような状態になっているはずです。
データの参照
Unity上のFirebaseManagerのis Read
とis Json
にチェックをしてUnityを再生してください。
Read: {"atk":10,"hp":5}
UnityEngine.Debug:Log (object)
FirebaseManager/<>c__DisplayClass5_0:<ReadQuestData>b__0 (System.Threading.Tasks.Task`1<Firebase.Database.DataSnapshot>) (at Assets/Scripts/FirebaseManager.cs:73)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback ()
とログが出れば大丈夫です。
設定した aaa ユーザーのhpとatkが取得出来ていますね。
データの書き込み
Unity上のFirebaseManagerのis Read
のチェックを外し、is Json
にチェックをしてUnityを再生してください。
一番下に ddd ユーザーのデータが出来ればOKです。
データの書き換え
Unity上のFirebaseManagerのis Read
のチェックを外し、is Json
のチェックも外してUnityを再生してください。
hpが 8 → 5 になっていればOKです。
以上で完了です。