LoginSignup
5
5

More than 3 years have passed since last update.

UnityのWebGLビルドでFirestoreからリアルタイムにデータを取得して反映する

Last updated at Posted at 2020-12-07

Peek 2020-12-07 18-30.gif

概要

UnityのWebGLビルドしたものからfirestoreにアクセスしたい

firebaseのSDKでWebGLで動作するものがないのでちょっと工夫する必要がある
流れとしては

  1. C#からjslibの関数を呼び出し
  2. jslib内でデータの取得をしたらSendMessage関数でC#の更新用の関数を呼び出し

jslibの作成

Assets配下にPluginsというディレクトリを作成して.jslibという拡張子のファイルを作成
ES2015以降の記法は使えないので注意

firestore.jslib

mergeInto(LibraryManager.library, {
  // 関数呼び出し
  Hello: function () {
    window.alert("Hello, world!");
  },
  Firestore: function() {
      // firebaseのconfig
      var firebaseConfig = {
          apiKey: "xxxxxxxxxxxxxxxxx",
          authDomain: "xxxxxxxxxxxxxxxxxxxxxxx",
          databaseURL: "xxxxxxxxxxxxxxxxxxx",
          projectId: "xxxxxxxxxxxxxxxxx",
          storageBucket: "xxxxxxxxxxxxxxxxxxxx",
          messagingSenderId: "xxxxxxxxxxxxxxxxxx",
          appId: "xxxxxxxxxxxxxxxxxxxxxxx"

      }
      // firebaseの初期化
      firebase.initializeApp(firebaseConfig);
      var db = firebase.firestore();
      db.collection("unity").doc("IHzXZcKpKwOiVFEVPbYT")
      .onSnapshot(function(doc) {
        console.log("Current data: ", doc.data());
        SendMessage('Text', 'UpdateText', doc.data().text);
    });
  }
});

C#側のスクリプト

以下のスクリプトを空オブジェクトなんかにつけておく

TextManager.cs
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;

public class TextManager : MonoBehaviour
{

    [DllImport("__Internal")]
    private static extern void Firestore();

// js側から更新が合った時に呼び出される関数
    public void UpdateText(string newText)
    {
// テキストコンポーネントの取得
        Text text = GameObject.Find("Text").GetComponent<Text>();
        text.text = newText;
    }


    void Start()
    {
//js側の関数を呼び出してデータの監視開始
        Firestore();
    }
}

ビルドしてできたindex.htmlでfirebaseSDKを読み込むように修正

WebGLようにビルドするとindex.htmlが表示されるので微修正

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | firestore-test</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
    <script src="TemplateData/UnityProgress.js"></script>
    <script src="Build/UnityLoader.js"></script>
    <script>
      var unityInstance = UnityLoader.instantiate("unityContainer", "Build/Build.json", {onProgress: UnityProgress});
    </script>
  </head>
  <body>
    <div class="webgl-content">
      <div id="unityContainer" style="width: 960px; height: 600px"></div>
      <div class="footer">
        <div class="webgl-logo"></div>
        <div class="fullscreen" onclick="unityInstance.SetFullscreen(1)"></div>
        <div class="title">firestore-test</div>
      </div>
    </div>
    // ここでfirebaseを読み込む
    <script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-app.js"></script> 
    <script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-firestore.js"></script>
  </body>
</html>

おまけ

同じ様なやり方でデータの追加や更新もできるのでセーブデータとかの管理に使えるかも

参考

5
5
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
5
5