///
/// 加载GLB/GLTF模型
///
public class LoadGLB_GLTFUtility :MonoBehaviour
{
Action action;
public GameObject ObjOfImport;
bool isCreate = true;
private static LoadGLB_GLTFUtility instance;
public static LoadGLB_GLTFUtility Instance
{
get
{
if (instance == null)
{
GameObject obj = new GameObject();
obj.name = "LoadGLBUtility";
instance = obj.AddComponent();
}
return instance;
}
}
///
/// 导入网络glb资源
///
/// 模型路径
/// 导入完成事件
public void ImportGLB_GLTFAsyncByWed(string url, Action action)
{
StartCoroutine(DownLoadFile(url, action));
}
///
/// 导入网络glb资源
///
/// 路径
public void ImportGLBAsyncByWed(string url)
{
StartCoroutine(DownLoadFile(url, null));
}
///
/// 下载网络资源到本地
///
///
///
IEnumerator DownLoadFile(string url,Action action)
{
yield return new WaitForSeconds(0.5f);
string directoryPath = Application.persistentDataPath + "/FileCache";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string downloadFileName = url.Substring(url.LastIndexOf('/') + 1);
string localpath = directoryPath + "/" + downloadFileName;
Debug.Log(downloadFileName);
//如果本地文件已存在 直接加载
if (File.Exists(localpath))
{
ImportGLB_GLTFAsync(localpath, action);
yield break;
}
UnityWebRequest webRequest = UnityWebRequest.Get(url);
webRequest.timeout = 60;
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log("Download Error: " + webRequest.error);
if (File.Exists(localpath))
{
File.Delete(localpath);
}
}
else
{
var file = webRequest.downloadHandler.data;
FileStream nFile = new FileStream(localpath, FileMode.Create);
nFile.Write(file, 0, file.Length);
nFile.Close();
ImportGLB_GLTFAsync(localpath, action);
}
}
///
/// 异步加载 gltf and glb
///
/// 路径
/// 回调函数
public void ImportGLB_GLTFAsync(string filepath, Action action)
{
if (!isCreate) return;
isCreate = false;
UnloadAndDestroy(ObjOfImport);
Importer.LoadFromFileAsync(filepath, new ImportSettings(), OnFinishAsync);
this.action = action;
}
///
///异步加载模型
///
/// <路径/param>
public void ImportGLB_GLTFAsync(string filepath)
{
if (!isCreate) return;
isCreate = false;
UnloadAndDestroy(ObjOfImport);
Importer.LoadFromFileAsync(filepath, new ImportSettings(), OnFinishAsync);
}
///
/// 完成加载
///
/// 加载出来的物体
/// 加载的动画
///
///
void OnFinishAsync(GameObject result, AnimationClip[] clip, Transform loadpos, string sign)
{
ObjOfImport = result;
isCreate = true;
Debug.Log("Finished importing " + result.name);
if (action != null)
action();
}
///
/// 删除卸载 所有加载过的模型 清除缓存
///
///
public void UnloadAndDestroy(GameObject obj)
{
if (obj != null)
{
GameObject.Destroy(obj);
}
Resources.UnloadUnusedAssets();
}
}