11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HTMLと連携するアプリはUnityよりthree.jsのほうが相性がよかった話

Last updated at Posted at 2019-12-02

Unity(WebGL)のオブジェクトを親のjavascriptから入力するアプリを作成していたが
https://structuralengine.github.io/FrameWebforJS
開発が進まなくって three.js に変えました

Unity(WebGL)と親のjavascriptとの連携方法は以下の通りです。

こんな感じでjavascript と unity を連携させる
image.png

Unity スクリプトから JavaScript 関数を呼び出す

プロジェクトでブラウザJavaScriptを使用する推奨方法は、JavaScriptソースをプロジェクトに追加し、それらの関数をスクリプトコードから直接呼び出すことです。そのためには、Assetsフォルダーの「Plugins」サブフォルダーの下に、.jslib拡張子を使用してJavaScriptコードを含むファイルを配置します。プラグインファイルには、次のような構文が必要です。

○○.jslib

mergeInto(LibraryManager.library, {

  ReceiveUnity: function (str) {
    window.ReceiveUnity(Pointer_stringify(str));
  }

});

次に、上記の関数を以下のように C# スクリプトから呼び出します。

○○.cs
using UnityEngine;
using System.Runtime.InteropServices;

public class NewBehaviourScript : MonoBehaviour {

  [DllImport("__Internal")]
  private static extern void ReceiveUnity(string message);

  void Start() {
      ReceiveUnity("This is a string.");
  }
}

Unity スクリプト関数を JavaScript から 呼び出す

ブラウザーの JavaScript から Unity スクリプトにデータや通知の送信が必要な場合があります。推奨される方法は、コンテンツ内でゲームオブジェクトのメソッドを呼び出すことです。プロジェクトに埋め込まれた JavaScript プラグインから呼び出しを行う場合は、以下のコードを使用します。

SendMessage(objectName, methodName, value);

objectName はシーンのオブジェクトの名。 methodName は、現在オブジェクトにアタッチされているスクリプトのメソッド名です。value には文字列、数字などで、以下の例のように空にしておくことも可能です。

SendMessage('MyGameObject', 'MyFunction');
SendMessage('MyGameObject', 'MyFunction', 5);

SendMessage('MyGameObject', 'MyFunction', 'MyString');

Unity を辞めて three.js に変えた理由

unity は unity エディタで開発するので javascript の連携は仕様が明確になっていないと開発できない

まるで、2つの別のアプリを作っているようだった

three.js に変えてみて

複雑な3D表現をするわけではないので three.js で十分
むしろ近年の three.js は unity に劣らないほど充実している

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?