LoginSignup
47

More than 5 years have passed since last update.

unity-webview で自前のHTMLを表示するサンプル

Last updated at Posted at 2014-06-11

gree/unity-webview

unity-webview 備え付けのサンプルアプリがうまく動かなかったので自前でサンプルを作ってみた。

1. 空のシーンを作る

2. シーンに空の GameObject を追加する

3. 2.のGameObjectに WebViewObject をアタッチする

4. 以下のスクリプトを MyWebView.cs などの名前で保存して、3.のGameObjectにアタッチする

MyWebView.cs
using UnityEngine;
using System.Collections;
using System.IO;

public class MyWebView : MonoBehaviour {
    // Inspector で画面上に配置した GUI Text にアタッチする
    public GUIText DebugText;

    string m_filePath;

    void Start() {
        m_filePath = Path.Combine(Application.persistentDataPath, "sample.html");
        Debug.Log (m_filePath);
        PrepareHTML();

        // このスクリプトがアタッチされているGameObjectからWebViewObjectを取得する
        var webview = GetComponent<WebViewObject>();

        // WebViewObject の初期化時にWebページ側から呼び出すことができるコールバック関数を定義する。
        // Web側からコールバック関数呼び出すには、リンク要素の href 属性などURLを指定する箇所で
        // 'unit:(任意の文字列)' のように指定すると、コールバック関数が呼び出される。
       // このとき、"(任意の文字列)"の部分が関数の引数として渡される。
        webview.Init ((string msg) => {
            Debug.Log ("Call from Web view : " + msg);
            DebugText.text = msg;
        });
        webview.LoadURL("file://" + m_filePath);
        webview.SetVisibility(true);
        webview.SetMargins(10,100,10,10);
    }

    void PrepareHTML() {
        using(var writer = new StreamWriter(m_filePath, false)) {
            writer.Write(
@"<html>
<body>
Hello unity-webview !!!<br/>
<ul>
  <li><a href='unity:hoge'>callback 'hoge'</a></li>
  <li><a href='unity:fuga'>callback 'fuga'</a></li>
</ul>
</body>
</html>
");
            writer.Close();
        }
    }
}

5. シーンに GUIText を配置する

6. 5.のGUITextを Inspector 上で、4.でアタッチした MyWebView スクリプトの Debug Text にドラッグして関連付ける

kobito.1402493240.498332.png

iOS 向けにビルドして、以下のように表示されたらOK。
"callback〜" のリンクをタップすると、画面上の文字が "hoge" とか "fuga" とかに切り替わることを確認する。

kobito.1402492549.127133.png

サンプルがうまく動かない場合の注意点

  • Player Settings の Company Name に空白などの文字が含まれていないか?

[Edit]-[Project Settings]-[Player] で Player Settings で Company Name の設定を確認し、この中にファイルパスとして使用すると問題が出るような文字が含まれていないことを確認する。

kobito.1402492766.263823.png

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
47