facebook twitter hatena line email

Unity/Firebase/Realtimedatabase/chat

提供: 初心者エンジニアの簡易メモ
2021年9月20日 (月) 14:11時点におけるAdmin (トーク | 投稿記録)による版 (ページの作成:「==chatサンプル== ChatScene.cs <pre> using UnityEngine; using UnityEngine.UI; using Firebase.Database; using System; public class ChatScene : MonoBehaviour { void...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

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;

        var now = DateTime.UtcNow;
        long unixtime = (long)(now - new DateTime(1970, 1, 1)).TotalSeconds;

        Msg msg = new Msg(key, text, 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;
    }
}