LoginSignup
7
2

More than 5 years have passed since last update.

[Unity]WebGL出力でダイアログからVRMを読み込む

Last updated at Posted at 2018-11-20

UnityのWebGLビルドで、ユーザーが好きなVRMを指定してゲームに読み込み、キャラクターとして使用する方法です。
読み込み部分は@mechamogeraさんの下記の記事ほぼそのまままです(感謝)

参考記事

「UnityのWebGL出力でHTMLのファイル選択ダイアログを表示して外部ファイルを読み込む」
https://qiita.com/mechamogera/items/89d4555b202af96810af

手順

UniVRMのインポート

https://github.com/dwango/UniVRM/releases
UnityPackageをダウンロードしてインポートします

Pluginの準備

上記の記事の、「uGUI上からファイルを読み込む方法」を使用します

記事内に記載されている「Assets/Plugins/FileImporter.jslib」を作成します。

スクリプトの準備

ImportButton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System;
using VRM;

public class ImportButton : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern void FileImporterCaptureClick();

    public void OnButtonPointerDown()
    {
        FileImporterCaptureClick();
    }

    public void FileSelected(string url)
    {
        StartCoroutine(LoadJson(url));
    }

    private IEnumerator LoadJson(string url)
    {
        print(url);
        WWW www = new WWW(url);
        while (!www.isDone)
        { 
            yield return null;
        }
        if (www.error == null)
        {
            LoadVRMClicked_WebGL(www.bytes);
        }
        else
        {
            print(www.error);
        }
    }

    void LoadVRMClicked_WebGL(Byte[] bytes)
    {
        var context = new VRMImporterContext();

        // GLB形式でJSONを取得しParseします
        context.ParseGlb(bytes);

        context.Load();
        OnLoaded(context);
    }

    private void OnLoaded(VRMImporterContext context)
    {
        //読込が完了するとcontext.RootにモデルのGameObjectが入っています
        var root = context.Root;

        //モデルをワールド上に配置します
        root.transform.position = new Vector3(0, 0, 0);
        root.transform.Rotate(new Vector3(0, 180, 0));

        //メッシュを表示します
        context.ShowMeshes();
    }
}

上記スクリプトを作成し、シーンに「ImportButton」という名前の空のゲームオブジェクトを作成してアタッチします。
(PluginのSendMessageはこの名前をキーにしているので異なると動作しません)

ボタンの準備

uGUIのボタンを用意して、Event Triggerコンポーネントをアタッチし、Pointer Downイベントに対してImportButton.OnButtonPointerDown()を割り当てます。

WebGL用にビルドして動作確認します。
うまく動かない場合は、プラウザの開発者モードのConsoleを見るとエラー内容を確認できます。

サンプル

プロジェクト一式
https://github.com/torikasyu/UnityWebGLVRM

unityroomにアップしたもの
https://unityroom.com/games/torikasyu_vrmloader

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