[技术干货] UnityGLTF不支持Android手机端不能读取StreamingAssets目录解决

[复制链接]

UnityGLTF不支持Android手机端不能读取StreamingAssets目录解决

发表于 2021-12-27 12:21:48 来自 技术干货 阅读模式 倒序浏览
923 0 查看全部
最近工作比较忙,已经2个多月没有写博客了。最近一直在一个VR办公会议的项目,也积累了一些东东需要写出来。
在项目中用到了gltf资源,用到UntiyGLTF这个开源工具,用来在云上或者StreamingAssets目录下读取文件,并且渲染出来。
但是在使用UnityGLTF时,在Android手机上,不支持读取StreamingAssets目录下的gltf文件。所以写个UnityWebRequestLoader来支持读取文件,使用了Unity的自带的WebRequest。
1、首先UnityWebRequest不支持await等待,需要进行对他进行扩展支持
  1. ‹font size="3">  public static class UnityGLTFExtension {
  2.   public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
  3.   {
  4.     var tcs = new TaskCompletionSource‹object>();
  5.     asyncOp.completed += obj => { tcs.SetResult(null); };
  6.     return ((Task)tcs.Task).GetAwaiter();
  7.   }
  8.   }‹/font>
复制代码

2、增加UnityWebRequestLoader的loader插件,支持android读取StreamingAssets目录下的文件
  1. ‹font size="3">using System;
  2. using System.IO;
  3. using System.Runtime.CompilerServices;
  4. using System.Threading.Tasks;
  5. using UnityEngine;
  6. using UnityEngine.Networking;

  7. namespace UnityGLTF.Loader
  8. {
  9.   public static class UnityGLTFExtension {
  10.   public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
  11.   {
  12.     var tcs = new TaskCompletionSource‹object>();
  13.     asyncOp.completed += obj => { tcs.SetResult(null); };
  14.     return ((Task)tcs.Task).GetAwaiter();
  15.   }
  16.   }


  17.   public class UnityWebRequestLoader : ILoader
  18.   {
  19.   public Stream LoadedStream { get; private set; }

  20.   public bool HasSyncLoadMethod => false;

  21.   private string _rootUri;

  22.   public UnityWebRequestLoader(string rootUri)
  23.   {
  24.     _rootUri = rootUri;
  25.   }


  26.   public async Task LoadStream(string gltfFilePath)
  27.   {
  28.     if (gltfFilePath == null)
  29.     {
  30.       throw new ArgumentNullException(nameof(gltfFilePath));
  31.     }

  32.     string pathToLoad = Path.Combine(_rootUri, gltfFilePath);

  33.     var getRequest = UnityWebRequest.Get(pathToLoad);
  34.     await getRequest.SendWebRequest();

  35.     byte[] data = getRequest.downloadHandler.data;
  36.     if (data == null || data.Length == 0)
  37.     {
  38.       throw new InvalidOperationException(string.Format(
  39.       "Failed to load from '{0}' - file was empty!", pathToLoad));
  40.     }
  41.     LoadedStream = new MemoryStream(data.Length);
  42.     await LoadedStream.WriteAsync(data, 0, data.Length);
  43.   }

  44.   public void LoadStreamSync(string jsonFilePath)
  45.   {
  46.     throw new NotImplementedException();
  47.   }
  48.   }
  49. }‹/font>
复制代码

3、包装一下gltf load,支持http/https,android手机加载,普通pc加载
  1. ‹font size="3">  public static async Task‹GameObject> Load(string gltfUrl, Transform parent)
  2.   {
  3.   GameObject obj = null;
  4.   GLTFSceneImporter sceneImporter = null;
  5.   ILoader loader = null;
  6.   string directoryPath = URIHelper.GetDirectoryName(gltfUrl);
  7.   try
  8.   {
  9.     if (gltfUrl.StartsWith("http://") || gltfUrl.StartsWith("https://"))
  10.     {
  11.       loader = new WebRequestLoader(directoryPath);

  12.       sceneImporter = new GLTFSceneImporter(
  13.       URIHelper.GetFileFromUri(new Uri(gltfUrl)),
  14.       loader,
  15.       asyncCoroutineHelper
  16.       );
  17.     }
  18.     else if (gltfUrl.StartsWith("jar:file://"))
  19.     {
  20.       loader = new UnityWebRequestLoader(directoryPath);

  21.       sceneImporter = new GLTFSceneImporter(
  22.       Path.GetFileName(gltfUrl),
  23.       loader,
  24.       asyncCoroutineHelper
  25.       );
  26.     }
  27.     else
  28.     {
  29.       loader = new FileLoader(directoryPath);
  30.       sceneImporter = new GLTFSceneImporter(
  31.       Path.GetFileName(gltfUrl),
  32.       loader,
  33.       asyncCoroutineHelper
  34.       );
  35.     }

  36.     sceneImporter.SceneParent = parent;
  37.     sceneImporter.Collider = GLTFSceneImporter.ColliderType.None;
  38.     sceneImporter.MaximumLod = 300;
  39.     sceneImporter.IsMultithreaded = true;

  40.     await sceneImporter.LoadSceneAsync();

  41.     obj = sceneImporter.CreatedObject;
  42.   }
  43.   finally
  44.   {
  45.     if (loader != null)
  46.     {
  47.       sceneImporter?.Dispose();
  48.       sceneImporter = null;
  49.       loader = null;
  50.     }
  51.   }

  52.   return obj;
  53.   }‹/font>
复制代码

4、根据不同的平台,组装streamingassets目录
  1. ‹font size="3">  private string streamingAssetsPath;
  2.   streamingAssetsPath =
  3. #if UNITY_EDITOR
  4.     Application.streamingAssetsPath;
  5. #else
  6.     "jar:file://" + Application.dataPath + "!/assets";
  7. #endif

  8. GameObject rootObject = await Gltf.Load(streamingAssetsPath + "test.glb", parentTransform);‹/font>
复制代码

这样就可以支持android手机也可以在StreamingAssets目录下读取gltf/glb文件了。




来源:网络转载
回复

使用道具 举报

游客~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|极客同行 ( 蜀ICP备17009389号-1 )

© 2013-2016 Comsenz Inc. Powered by Discuz! X3.4