LoginSignup
21
15

More than 5 years have passed since last update.

Firebase-Unityを使って簡単なChatを作ってみた話

Last updated at Posted at 2016-11-06

概要

UnityにFirebaseのRealtimeDatabaseを導入して簡単なchatを作ってみた。
Unity版のFirebaseは、2016年11月6日現在、まだ完成していないようです。
よって、製品版では使わないほうが良いとのことです。
あくまでも自己責任でお願いします。

RealtimeDatabaseとは

DBに書き込んだ内容が、DBに接続しているPlatform(Android端末,ios端末など)に
即座に反映されます。
リアルタイムに会話するなどのchatアプリを作るときに導入すると良いと思います。

手順

(1)Firebaseのアカウントを作る
以下のサイトにてFirebaseのアカウントを作ります
https://console.firebase.google.com/

(2)プロジェクトの作成を行う
私の場合は、IOSを選択しましたが、Unityから使う分には問題なかったです。

スクリーンショット 2016-11-06 21.54.00.png

(3)GitHubよりfirebaseをCloneする
https://github.com/firebase/Firebase-Unity

(4)firebase.unitypackageをimportする
Unityプロジェクトを作成し、firebase.unitypackageをimportします。

こんな感じになります。
スクリーンショット 2016-11-06 21.58.52.png

この時点で、firebaseを導入できたことになります。

(5)Firebase-Unityのサンプルコードを元に実装してみる
Firebase-Unityにサンプルコードが載っています。
正しく動くとDataBaseの管理画面に、DBに送った内容が反映されます。

以下のような感じに反映されます。
スクリーンショット 2016-11-06 21.39.05.png

導入手順は以上です。

Chatを作ったときのサンプルコード

スクリーンショット 2016-11-06 21.38.33.png

IMG_8224.JPG
Unityプレイヤで発言した内容が、1秒以内にAndroid端末にも反映されました!

サンプルコード全体

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

public class FireBaseSample : MonoBehaviour {

    IFirebase root;
    IFirebase foo;
    public string userName = "userName";
    public string message = "message";
    public string output = "";

    void Awake() {
        root = Firebase.CreateNew("https://your-project-id.firebaseIO.com");
        foo = root.Child("root");
        //foo.Child (System.DateTime.Now.ToString ("yyyy-MM-dd-HH-mm-ss")).SetValue ("Awake");

    }

    void OnEnable() {
        foo.ChildAdded += FooChildAdded;
    }

    void OnDisable() {
        foo.ChildAdded -= FooChildAdded;
    }

    //DBに変更があったときに呼び出される
    void FooChildAdded (object sender, FirebaseChangedEventArgs e) {
        //Debug.Log("FooChildAdded: " + e.DataSnapshot.Key);
        //Debug.Log("Message: " + e.DataSnapshot.Child("Message").StringValue   );

        output +=  string.Format("{0}\nName:{1} Message:{2}", e.DataSnapshot.Key,e.DataSnapshot.Child("UserName").StringValue, e.DataSnapshot.Child("Message").StringValue);
        output += "\n";

    }

    void OnGUI() {
        if (GUI.Button (new Rect (210, 10, 150, 50), "Send")) 
        {
            print("Send!");
            string timestring = System.DateTime.Now.ToString ("yyyy-MM-dd-HH-mm-ss-zzz");

            //このやり方だと、FooChildAddedが呼び出されたとき、2つ以上の要素が取得できない
            //よってその下のjsonにして送るようにする
            //foo.Child (System.DateTime.Now.ToString (timestring)).Child ("UserName").SetValue (userName);
            //foo.Child (System.DateTime.Now.ToString (timestring)).Child ("Message").SetValue (message);

            //子項目は、一度にセット
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic ["UserName"] = userName;
            dic ["Message"] = message;

            var json = MiniJSON.Json.Serialize(dic);

            //Firebaseに登録する
            foo.Child (System.DateTime.Now.ToString (timestring)).SetJsonValue (json);
        }

        //ユーザ名セット
        userName = GUI.TextField(new Rect(10, 10, 200, 20), userName, 25);

        //メッセージ
        message = GUI.TextField(new Rect(10, 40, 200, 20), message, 25);

        //Output欄
        output = GUI.TextField(new Rect(10, 80, 400, 500), output);


    }


}

21
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
15