Skip to content

Instantly share code, notes, and snippets.

@hiroki-o
Created April 15, 2020 02:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroki-o/e283e7ea3b8453491512f33a45bd56ba to your computer and use it in GitHub Desktop.
Save hiroki-o/e283e7ea3b8453491512f33a45bd56ba to your computer and use it in GitHub Desktop.
FileOpenDialog Loader script (WebGL supported)
using System;
using System.Collections;
using System.Runtime.InteropServices;
using SFB;
using UnityEngine;
using VRM;
//
// Get SFB from https://github.com/gkngkc/UnityStandaloneFileBrowser
//
public class VrmRuntimeLoader : MonoBehaviour
{
#if UNITY_WEBGL && !UNITY_EDITOR
//
// WebGL
//
[DllImport("__Internal")]
private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);
public void DoLoadButton() {
Debug.Log("DoLoadButtonWebGL-WebGL");
UploadFile(gameObject.name, "OnFileUpload", ".vrm", false);
}
// Called from browser
public void OnFileUpload(string url) {
StartCoroutine(OutputRoutine(url));
}
#else
public void DoLoadButton()
{
var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", "vrm", false);
if (paths.Length > 0) {
StartCoroutine(OutputRoutine(new Uri(paths[0]).AbsoluteUri));
}
}
#endif
private IEnumerator OutputRoutine(string url)
{
var loader = new WWW(url);
yield return loader;
LoadVrm(loader.bytes);
}
static GameObject LoadVrm(Byte[] bytes)
{
var context = new VRMImporterContext();
// GLB形式でJSONを取得しParseします
context.ParseGlb(bytes);
try
{
// ParseしたJSONをシーンオブジェクトに変換していく
context.Load();
// バウンディングボックスとカメラの位置関係で見切れるのを防止する
context.EnableUpdateWhenOffscreen();
// T-Poseのモデルを表示したくない場合、ShowMeshesする前に準備する
// ロード後に表示する
context.ShowMeshes();
return context.Root;
}
catch(Exception ex)
{
Debug.LogError(ex);
// 関連するリソースを破棄する
context.Dispose();
throw;
}
}
}
@hiroki-o
Copy link
Author

#超ハッカソン 用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment