鳩の溜まり場

猫か鳩になりたい

Cloud FirestoreのUnity Packageがしれっとあったので簡単に使い方をまとめてみる【Unity】

世界のFirebase様、Unityにも対応してくれていて大変便利なんですが、現状他のFirebaseプロダクトのようなCloud FirestoreのUnity専用ドキュメントが無いので、簡単な使い方を備忘録としてまとめます。(2020/09/16現在)
ちっちゃい個人用のアプリで開発していた際の内容ですので、使えればヨシ!のスタンスです。
ただ、セキュリティ面等ご指摘ありましたらお願いします。泣いて喜びます。

下準備

基本的には他のFirebaseプロダクトの見様見真似で進めていきます。

firebase.google.com

ここのステップ5で、ダウンロードしてあるFirebase Unity SDKの中からFirebaseFirestore.unitypackageをUnityにImportします。

コーディング

Firestoreのusingディレクティブを利用

using Firebase.Firestore;

参照先を初期化

// 参照先の設定
FirebaseFirestore firestore = FirebaseFirestore.DefaultInstance;

データの追加

まずコード。

// 参照先
DocumentReference docRef = firestore.Collection("users").Document("YamadaTaro");
// YamadaTaroのデータ
Dictionary<string, System.Object> user = new Dictionary<string, System.Object>
{
    { "age", 20 },
    { "gender", "male" }
};

// Cloud Firestoreに追加
await docRef.SetAsync(user);

これを実行すると、

こんな感じに追加されます。

データの取得

Firestoreにこんな感じでデータを追加しておいて、これをUnity側から取得してみます。

コードはこんな感じ。

// 参照先
CollectionReference catsRef = firestore.Collection("cats");
// 取得
QuerySnapshot snapshot = await catsRef.GetSnapshotAsync();

// データの展開
foreach (DocumentSnapshot document in snapshot.Documents)
{
    // Nekotaro
    string name = document.Id;
    Debug.Log(name);

    // 猫の詳細データ
    Dictionary<string, object> data = document.ToDictionary();
    Debug.Log("age = " + data["age"]);
    Debug.Log("color = " + data["color"]);
}

実行すると

バッチリ取得できてます!

コードの全体像

using System.Collections.Generic;
using UnityEngine;
using Firebase.Firestore;

public class CloudFirestore : MonoBehaviour
{
    async void Start()
    {
        // 参照先の設定
        FirebaseFirestore firestore = FirebaseFirestore.DefaultInstance;

        // ---------- データの追加 ---------- //
        // 参照先
        DocumentReference docRef = firestore.Collection("users").Document("YamadaTaro");
        // YamadaTaroのデータ
        Dictionary<string, System.Object> user = new Dictionary<string, System.Object>
        {
            { "age", 20 },
            { "gender", "male" }
        };

        // Cloud Firestoreに追加
        await docRef.SetAsync(user);

        // ---------- データの取得 ---------- //
        // 参照先
        CollectionReference catsRef = firestore.Collection("cats");
        // 取得
        QuerySnapshot snapshot = await catsRef.GetSnapshotAsync();

        // データの展開
        foreach (DocumentSnapshot document in snapshot.Documents)
        {
            // Nekotaro
            string name = document.Id;
            Debug.Log(name);

            // 猫の詳細データ
            Dictionary<string, object> data = document.ToDictionary();
            Debug.Log("age = " + data["age"]);
            Debug.Log("color = " + data["color"]);
        }
    }
}

最後に

Unityのためのドキュメントがないだけで、C#用のドキュメントは存在してるので、これ以上のことを色々やりたい場合はそちらをみていただければより理解が深まると思います。

firebase.google.com

firebase.google.com