facebook twitter hatena line email

「Unity/Firebase/CloudFunctions」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(firebaseのサーバー側変更)
(サンプル)
行13: 行13:
  
 
==サンプル==
 
==サンプル==
 +
<pre>
 
  ScoreEntry score = new ScoreEntry();
 
  ScoreEntry score = new ScoreEntry();
 
  AddEntry(score);
 
  AddEntry(score);
 
+
</pre>
using System.Threading.Tasks;
+
<pre>
    class ScoreEntry {
+
using System.Threading.Tasks;
        public string Name = "taro";
+
class ScoreEntry {
        public int Age = 100;
+
    public string Name = "taro";
    }
+
    public int Age = 100;
    async Task<object> AddEntryAsync(ScoreEntry score)
+
}
 +
async Task<object> AddEntryAsync(ScoreEntry score)
 +
{
 +
    object data = new Dictionary<object, object>
 
     {
 
     {
         object data = new Dictionary<object, object>
+
         { "name", score.Name },
 +
        { "age", score.Age },
 +
    };
 +
    return await functions.GetHttpsCallable("addEntry").CallAsync(data)
 +
        .ContinueWith(task =>
 
         {
 
         {
             { "name", score.Name },
+
             return task.Result.Data;
            { "age", score.Age },
+
        });
        };
+
}
        return await functions.GetHttpsCallable("addEntry").CallAsync(data)
+
void AddEntry(ScoreEntry score)
            .ContinueWith(task =>
+
{
            {
+
    AddEntryAsync(score).ContinueWith(task =>
                return task.Result.Data;
+
            });
+
    }
+
    void AddEntry(ScoreEntry score)
+
 
     {
 
     {
         AddEntryAsync(score).ContinueWith(task =>
+
         if (task.IsFaulted)
 
         {
 
         {
             if (task.IsFaulted)
+
             // onError
            {
+
        }
                // onError
+
        else
            }
+
        {
            else
+
            // onComplete
 +
            Debug.Log("task.Result=" + task.Result); // OK
 +
        }
 +
    }, TaskScheduler.FromCurrentSynchronizationContext());
 +
}
 +
 
 +
[Serializable]
 +
class ResData
 +
{
 +
    public string status = "ok";
 +
    public string notice = "";
 +
    public List<ResUser> users;
 +
}
 +
[Serializable]
 +
class ResUser
 +
{
 +
    public int point = 0;
 +
    public string name = "";
 +
}
 +
void GetTopEntries()
 +
{
 +
    GetTopEntriesAsync().ContinueWith(task =>
 +
    {
 +
        if (task.IsFaulted)
 +
        {
 +
            // onError
 +
        }
 +
        else
 +
        {
 +
            // onComplete
 +
            string json = task.Result.ToString();
 +
            Debug.Log("json=" + json);
 +
            ResData resData = JsonUtility.FromJson<ResData>(json);
 +
            Debug.Log("status=" + resData.status);
 +
            Debug.Log("notice=" + resData.notice);
 +
            foreach (ResUser user in resData.users)
 
             {
 
             {
                 // onComplete
+
                 Debug.Log("user.name=" + user.name);
                 Debug.Log("task.Result=" + task.Result); // OK
+
                 Debug.Log("user.point=" + user.point);
 
             }
 
             }
         }, TaskScheduler.FromCurrentSynchronizationContext());
+
         }
    }
+
    }, TaskScheduler.FromCurrentSynchronizationContext());
 +
}
 +
</pre>
  
 
==firebaseのサーバー側変更==
 
==firebaseのサーバー側変更==

2019年8月7日 (水) 01:16時点における版

準備

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

import

FirebaseFunctions.unitypackage をunityのAssets/ImportPackage/CustomPackageからImportする

初期化

using Firebase.Functions;
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;

東京リージョンの場合こちらを記述

using Firebase.Functions;
FirebaseFunctions functions = FirebaseFunctions.GetInstance("asia-northeast1");

サンプル

 ScoreEntry score = new ScoreEntry();
 AddEntry(score);
using System.Threading.Tasks;
class ScoreEntry {
    public string Name = "taro";
    public int Age = 100;
}
async Task<object> AddEntryAsync(ScoreEntry score)
{
    object data = new Dictionary<object, object>
    {
        { "name", score.Name },
        { "age", score.Age },
    };
    return await functions.GetHttpsCallable("addEntry").CallAsync(data)
        .ContinueWith(task =>
        {
            return task.Result.Data;
        });
}
void AddEntry(ScoreEntry score)
{
    AddEntryAsync(score).ContinueWith(task =>
    {
        if (task.IsFaulted)
        {
            // onError
        }
        else
        {
            // onComplete
            Debug.Log("task.Result=" + task.Result); // OK
        }
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

[Serializable]
class ResData
{
    public string status = "ok";
    public string notice = "";
    public List<ResUser> users;
}
[Serializable]
class ResUser
{
    public int point = 0;
    public string name = "";
}
void GetTopEntries()
{
    GetTopEntriesAsync().ContinueWith(task =>
    {
        if (task.IsFaulted)
        {
            // onError
        }
        else
        {
            // onComplete
            string json = task.Result.ToString();
            Debug.Log("json=" + json);
            ResData resData = JsonUtility.FromJson<ResData>(json);
            Debug.Log("status=" + resData.status);
            Debug.Log("notice=" + resData.notice);
            foreach (ResUser user in resData.users)
            {
                Debug.Log("user.name=" + user.name);
                Debug.Log("user.point=" + user.point);
            }
        }
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

firebaseのサーバー側変更

functions.https.onCall を使ってシリアル&認証トークンで接続するようにする

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// 追加
exports.addEntry = functions
  .region('asia-northeast1')
  .https.onCall((data, context) =>
{
  const entry = {
    name : data.name,
    point : data.point
  };
  return admin.firestore().collection('entries')
    .add(entry)
    .then((snapshot) =>
  {
    return 'OK';
  });
});
// 更新
exports.replaceEntry = functions
  .region('asia-northeast1')
  .https.onCall((data, context) =>
{
  const entry = {
    name : data.name,
    point : data.point
  };
  return admin.firestore().collection('entries')
    .doc("ID1").set(entry)
    .then((snapshot) =>
  {
    return 'OK';
  });
});
//  トップcount件のEntryを取得
exports.getTopEntries = functions
  .region('asia-northeast1')
  .https.onCall((data, context) =>
{
  const count = data.count;
  return admin.firestore().collection('entries')
    .orderBy('point', 'desc')
    .limit(count)
    .get()
    .then((snapshot) =>
  {
    var obj = {
        status: 'ok',
        notice: '',
        users: snapshot.docs.map(x => x.data()),
    }
    var json=JSON.stringify(obj);
    return json;
  });
});

参考

https://firebase.google.com/docs/functions/callable?hl=ja

https://devlog.hassaku.blue/2019/03/unity-firebase-firebase.html

https://firebase.google.com/docs/reference/unity/class/firebase/functions/firebase-functions

https://github.com/firebase/quickstart-unity/blob/master/functions/testapp/Assets/Firebase/Sample/Functions/UIHandler.cs