【Unity】ランタイムでVRMをD&Dで読み込み表示する
2019-10-03 2019-11-16
画面上にドラッグアンドドロップをすることで,VRMを読み込み表示するまでの方法のメモ書き
Environment
- Unity2019.1.12f1
- Windows10 64bit (macOSは非対応)
Methods
UniVRMのインポート
全てはここから.UniVRMをDLしプロジェクト上にインポートを行う.
https://github.com/vrm-c/UniVRM
UnityWindowsFileDrag-Dropのインポート
WindowsのメッセージをUnityで受け取ることを簡単にできるようにするスクリプトをプロジェクトに入れる.
https://github.com/Bunny83/UnityWindowsFileDrag-Drop/blob/master/B83.Win32.cs
D&Dしたファイルのpathを受け取りUniVRMでランタイムロードする
D&DしたファイルのパスをUnity側で受け取り,そのパスをUniVRMのランタイムロードするためのメソッドに渡してインスタンスを作成する.
以下がサンプルソース
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
using System.Collections.Generic; using UnityEngine; using B83.Win32; using System; using VRM; using System.Collections; public class FileDragAndDrop : MonoBehaviour { UnityDragAndDropHook hook; void OnEnable() { // must be created on the main thread to get the right thread id. hook = new UnityDragAndDropHook(); hook.InstallHook(); hook.OnDroppedFiles += OnFiles; } void OnDisable() { hook.UninstallHook(); } void OnFiles(List<string> aFiles, POINT aPos) { var path = aFiles[0]; LoadVRM(path); } private void LoadVRM(string path) { StartCoroutine(LoadVrmCoroutine(path, go => { go.transform.position = new Vector3(1, 1, 1); })); } private IEnumerator LoadVrmCoroutine(string path, Action<GameObject> onLoaded) { var www = new WWW(path); yield return www; VRMImporter.LoadVrmAsync(www.bytes, onLoaded); } } |
これを適当なオブジェクトに貼り付けて後はビルドするだけ.UnityEditor上だとD&Dができないので注意.