最近工作比较忙,已经2个多月没有写博客了。最近一直在一个VR办公会议的项目,也积累了一些东东需要写出来。
在项目中用到了gltf资源,用到UntiyGLTF这个开源工具,用来在云上或者StreamingAssets目录下读取文件,并且渲染出来。
但是在使用UnityGLTF时,在Android手机上,不支持读取StreamingAssets目录下的gltf文件。所以写个UnityWebRequestLoader来支持读取文件,使用了Unity的自带的WebRequest。
1、首先UnityWebRequest不支持await等待,需要进行对他进行扩展支持
public static class UnityGLTFExtension {
public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
{
var tcs = new TaskCompletionSource<object>();
asyncOp.completed += obj => { tcs.SetResult(null); };
return ((Task)tcs.Task).GetAwaiter();
}
}
2、增加UnityWebRequestLoader的loader插件,支持android读取StreamingAssets目录下的文件
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace UnityGLTF.Loader
{
public static class UnityGLTFExtension {
public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
{
var tcs = new TaskCompletionSource<object>();
asyncOp.completed += obj => { tcs.SetResult(null); };
return ((Task)tcs.Task).GetAwaiter();
}
}
public class UnityWebRequestLoader : ILoader
{
public Stream LoadedStream { get; private set; }
public bool HasSyncLoadMethod => false;
private string _rootUri;
public UnityWebRequestLoader(string rootUri)
{
_rootUri = rootUri;
}
public async Task LoadStream(string gltfFilePath)
{
if (gltfFilePath == null)
{
throw new ArgumentNullException(nameof(gltfFilePath));
}
string pathToLoad = Path.Combine(_rootUri, gltfFilePath);
var getRequest = UnityWebRequest.Get(pathToLoad);
await getRequest.SendWebRequest();
byte[] data = getRequest.downloadHandler.data;
if (data == null || data.Length == 0)
{
throw new InvalidOperationException(string.Format(
"Failed to load from '{0}' - file was empty!", pathToLoad));
}
LoadedStream = new MemoryStream(data.Length);
await LoadedStream.WriteAsync(data, 0, data.Length);
}
public void LoadStreamSync(string jsonFilePath)
{
throw new NotImplementedException();
}
}
}
3、包装一下gltf load,支持http/https,android手机加载,普通pc加载
public static async Task<GameObject> Load(string gltfUrl, Transform parent)
{
GameObject obj = null;
GLTFSceneImporter sceneImporter = null;
ILoader loader = null;
string directoryPath = URIHelper.GetDirectoryName(gltfUrl);
try
{
if (gltfUrl.StartsWith("http://") || gltfUrl.StartsWith("https://"))
{
loader = new WebRequestLoader(directoryPath);
sceneImporter = new GLTFSceneImporter(
URIHelper.GetFileFromUri(new Uri(gltfUrl)),
loader,
asyncCoroutineHelper
);
}
else if (gltfUrl.StartsWith("jar:file://"))
{
loader = new UnityWebRequestLoader(directoryPath);
sceneImporter = new GLTFSceneImporter(
Path.GetFileName(gltfUrl),
loader,
asyncCoroutineHelper
);
}
else
{
loader = new FileLoader(directoryPath);
sceneImporter = new GLTFSceneImporter(
Path.GetFileName(gltfUrl),
loader,
asyncCoroutineHelper
);
}
sceneImporter.SceneParent = parent;
sceneImporter.Collider = GLTFSceneImporter.ColliderType.None;
sceneImporter.MaximumLod = 300;
sceneImporter.IsMultithreaded = true;
await sceneImporter.LoadSceneAsync();
obj = sceneImporter.CreatedObject;
}
finally
{
if (loader != null)
{
sceneImporter?.Dispose();
sceneImporter = null;
loader = null;
}
}
return obj;
}
4、根据不同的平台,组装streamingassets目录
private string streamingAssetsPath;
streamingAssetsPath =
#if UNITY_EDITOR
Application.streamingAssetsPath;
#else
"jar:file://" + Application.dataPath + "!/assets";
#endif
GameObject rootObject = await Gltf.Load(streamingAssetsPath + "test.glb", parentTransform);
这样就可以支持android手机也可以在StreamingAssets目录下读取gltf/glb文件了。
|