【Unity】基于GLTFUtility插件加载gltf格式数据


一、环境配置

1. GLTFUtility项目git地址

https://github.com/Siccity/GLTFUtility
gltf格式数据插件直接拖放至asset下即可

2. 安装支持工具:搜索Newtonsoft.Json并安装

在这里插入图片描述
https://github.com/JamesNK/Newtonsoft.Json

二、代码调用

1. 单线程加载GLTF/GLB

// Single thread
using Siccity.GLTFUtility;

void ImportGLTF(string filepath) {
    
    
   GameObject result = Importer.LoadFromFile(filepath);
}
void ImportGLB(string filepath) {
    
    
   GameObject result = Importer.LoadFromFile(filepath);
}

2. 多线程加载GLTF

// Multithreaded
using Siccity.GLTFUtility;

void ImportGLTFAsync(string filepath) {
    
    
   Importer.ImportGLTFAsync(filepath, new ImportSettings(), OnFinishAsync);
}

void OnFinishAsync(GameObject result, AnimationClip[] animations) {
    
    
   Debug.Log("Finished importing " + result.name);
}

3. 多线程加载GLB

// Multithreaded
using Siccity.GLTFUtility;

void ImportGLBAsync(string filepath) {
    
    
   Importer.ImportGLBAsync(filepath, new ImportSettings(), OnFinishAsync);
}

void OnFinishAsync(GameObject result, AnimationClip[] animations) {
    
    
   Debug.Log("Finished importing " + result.name);
}

三、加载参考案例

1. 创建基础UI

在这里插入图片描述

2. 挂接脚本到ReaderGLTF对象

在这里插入图片描述
将UI组件挂载到脚本参数。

    public Button addGLTF_Button;
	public Button addGLB_Button;
	public Button del_Button;

	public Text pathName;
	public Text text;
	public bool loaded = false;

	GameObject glTFObj;
	List<GameObject> glTFObjList;
	// Start is called before the first frame update
	void Start()
    {
    
    
		addGLTF_Button.onClick.AddListener(loadGLTF);//调用加载GLTF文件方法
		addGLB_Button.onClick.AddListener(loadGLB);//调用加载GLB文件方法
		del_Button.onClick.AddListener(unloadAll);//调用清除所有对象方法

		glTFObjList = new List<GameObject>();//创建列表用于存储模型对象
		
	}

参考上文第二节,补充相关代码。

3. 加载结果

在这里插入图片描述
测试数据:食人花动画模型

四、拓展说明

1. 拓展支持说明

注意,这个插件不支持EXT_texture_webp拓展。
在这里插入图片描述

2. 报错处理

如果glb格式数据加载出现报错
JsonReaderException: Unexpected character encountered while parsing value: g. Path ‘’, line 0, position 0."
建议转换为gltf格式再试试
再不行大概率就是这个gltf数据用到的拓展不被支持

3. 工具分享

一个gltf和glb在线免费互转工具
https://products.aspose.app/3d/zh-cn/conversion/glb-to-gltf

猜你喜欢

转载自blog.csdn.net/qq_35079107/article/details/130927848