facebook twitter hatena line email

Unity/Firebase/Realtimedatabase/chat

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

chatサンプル

ChatScene.cs

using UnityEngine;
using UnityEngine.UI;
using Firebase.Database;
using System;

public class ChatScene : MonoBehaviour
{
    void Start()
    {
        DatabaseReference userReference = FirebaseDatabase.DefaultInstance.GetReference("chatusers");
        userReference.ChildAdded += HandleChildAdded;
        userReference.ChildChanged += HandleChildChanged;
        userReference.ChildRemoved += HandleChildRemoved;
        DatabaseReference msgReference = FirebaseDatabase.DefaultInstance.GetReference("chatmsgs");
        msgReference.ChildAdded += ChatChildAdded;

        InputField input = GameObject.Find("/Canvas/InputField").GetComponent<InputField>();
        GameObject.Find("EnterButton").GetComponent<Button>().onClick.AddListener(delegate {
            AddUser(input.text);
        });
        InputField chatInput = GameObject.Find("/Canvas/ChatInputField").GetComponent<InputField>();
        GameObject.Find("ChatButton").GetComponent<Button>().onClick.AddListener(delegate {
            SendChatMsg(chatInput.text);
            chatInput.text = "";
        });
        // userReference.OnDisconnect();
        // DatabaseReference.GoOffline();
    }
    // 受信 追加された時
    void HandleChildAdded(object sender, ChildChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        string json = args.Snapshot.GetRawJsonValue();
        Debug.Log("HandleChildAdded=" + json); // {"email":"ttt@example","username":"ttt"}

        User user = JsonUtility.FromJson<User>(json);
        Debug.Log("HandleChildAdded username=" + user.username);
    }
    // 受信 更新された時
    void HandleChildChanged(object sender, ChildChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        string json = args.Snapshot.GetRawJsonValue();
        Debug.Log("HandleChildChanged=" + json); // {"email":"ttt@example","username":"ttt"}

        User user = JsonUtility.FromJson<User>(json);
        Debug.Log("HandleChildChanged username=" + user.username);
    }
    // 受信 削除された時
    void HandleChildRemoved(object sender, ChildChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        string json = args.Snapshot.GetRawJsonValue();
        Debug.Log("HandleChildRemoved=" + json); // {"email":"ttt@example","username":"ttt"}

        User user = JsonUtility.FromJson<User>(json);
        Debug.Log("HandleChildRemoved username=" + user.username);
    }
    // chat 受信 追加された時
    void ChatChildAdded(object sender, ChildChangedEventArgs args)
    {
        if (args.DatabaseError != null)
        {
            Debug.LogError(args.DatabaseError.Message);
            return;
        }
        string json = args.Snapshot.GetRawJsonValue();
        Debug.Log("ChatChildAdded=" + json);

        Msg msg = JsonUtility.FromJson<Msg>(json);
        GameObject.Find("Chat3Text").GetComponent<Text>().text = GameObject.Find("Chat2Text").GetComponent<Text>().text;
        GameObject.Find("Chat2Text").GetComponent<Text>().text = GameObject.Find("Chat1Text").GetComponent<Text>().text;
        Text chat1 = GameObject.Find("Chat1Text").GetComponent<Text>();
        chat1.text = msg.text + "(" + msg.timestamp +")";
    }
    // 送信
    void AddUser(string name)
    {
        User user = new User(name, name + "@example");
        string json = JsonUtility.ToJson(user); // {"email":"ttt@example","username":"ttt"}
#if Unity_EDITOR
        string userId = "pc";
#elif UNITY_ANDROID
        string userId = "android";
#elif UNITY_IPHONE
        string userId = "iphone";
#endif
        FirebaseDatabase.DefaultInstance.GetReference("chatusers").Child(userId)
            .SetRawJsonValueAsync(json);
    }
    void SendChatMsg(string text)
    {
        // userに存在しないキーを生成
        string key = FirebaseDatabase.DefaultInstance.GetReference("chatmsgs").Push().Key;

        Msg msg = new Msg(key, text, 0);
        json = json.Replace("\"unixtime\":0", "\"unixtime\":{\".sv\" : \"timestamp\"}"); // unixtimeをサーバー日時で設定

        string json = JsonUtility.ToJson(msg);
        FirebaseDatabase.DefaultInstance.GetReference("chatmsgs").Child(key)
            .SetRawJsonValueAsync(json);
    }
}

User.cs

public class User
{
    public string username;
    public string email;

    public User()
    {
    }

    public User(string username, string email)
    {
        this.username = username;
        this.email = email;
    }
}

Msg.cs

public class Msg
{
    public string key;
    public string text;
    public long timestamp;

    public Msg()
    {
    }

    public Msg(string key, string text, long timestamp)
    {
        this.key = key;
        this.text = text;
        this.timestamp = timestamp;
    }
}