facebook twitter hatena line email

Unity/Firebase/Realtimedatabase

提供: 初心者エンジニアの簡易メモ
2020年11月14日 (土) 17:48時点におけるAdmin (トーク | 投稿記録)による版 (サンプル)

移動: 案内検索

Realtimedatabaseのインストール

FirebaseDatabase.unitypackageをAssets/Importからインストールする

https://firebase.google.com/download/unity?hl=ja

料金課金周り

Gcp/Firebase/RealtimeDatabase [ショートカット]

ルール

以下のようなルールになってると、更新できないので、test時は修正後のように 修正前

{
  "rules": {
    ".read": false,
    ".write": false
  }
}

修正後

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

サンプル

SampleScene.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using Firebase;
using Firebase.Database;
using Firebase.Unity.Editor;

public class SampleScene : MonoBehaviour
{
    void Start()
    {
        // Get the root reference location of the database.
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

        // 書き込み
        FirebaseDatabase.DefaultInstance.GetReference("users")
        .Child("name")
        .SetValueAsync("taro");

        // 読み込み
        FirebaseDatabase.DefaultInstance.GetReference("users")
        .Child("name")
        .GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                Debug.LogError("not found users");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapShot = task.Result;
                Debug.Log(snapShot.Value);
        }
        });

    }
}

参考:https://firebase.google.com/docs/database/unity/retrieve-data?hl=ja

参考:http://siguma-sig.hatenablog.com/entry/2018/09/30/213822

変更があったら呼び出し

public class SampleScene : MonoBehaviour
{
    void Start()
    {
        // Get the root reference location of the database.
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

        // 変更があったら呼び出し
        FirebaseDatabase.DefaultInstance.GetReference("user")
            .Child("name").ValueChanged += HandleNameValueChanged;

        // 書き込み
        FirebaseDatabase.DefaultInstance.GetReference("user")
        .Child("name")
        .SetValueAsync("taro");
    }
    private void HandleNameValueChanged(object sender, ValueChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        Debug.Log("HandleNameValueChanged=" + args.Snapshot.Value);
    }
}