LoginSignup
11
7

More than 5 years have passed since last update.

【Unity】Webページ側からWebGLの関数を呼び出す

Last updated at Posted at 2015-05-09

概要

WebGLからWebページ側の関数を呼び出すという内容の続きで、今度は逆にWebページ側からWebGLの関数を呼び出すということをやりました。
Web Playerと同様にWebページ側で記述したSendMessage()でそのやりとりを行います。

以下はそのサンプルの手順です

Unity側

スクリーンショット 2015-05-08 22.06.00.png

具体的なUnityでの作業内容は説明しませんが、簡単に言うと赤玉(Sphere)を作って、それをprefab化して動的に生成されるようにします。
ボタンをクリックすれば、浮かんでるCubeから赤玉が産み出されるようなイメージです。

スクリプトは以下の通りです。これを「sample」という名をつけた空のオブジェクトにアタッチします。

test

var tama : Transform;

function tamaide () {
        Instantiate(tama,transform.position,transform.rotation);
}

Webサイト側

出力された「index.html」を開いて編集します。

表示さえされればいいので、適当な位置に<button>タグを追記


<center>
      <button>スーパー玉出</botton>
</center>

</body>直前の<script></script>タグ内に以下のスクリプトを追記します。


var s = document.querySelector("button");

s.addEventListener("click", function() {
    SendMessage("sample", "tamaide");
});

SendMessage()の第1引数に「object名」を第2引数に「関数名」で引数に渡すパラメータを指定して、「tamaide」を呼び出します。
これでボタンがクリックされる度に、赤玉が生成されて出てきます。

実行・検証

せっかくなので動画で

https://www.youtube.com/watch?v=V8_8INlGCCE&feature=youtu.be

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