TriLib2:Unity运行时运行时加载模型

概述

本文基于此版本

TriLib 2 是 Unity 的一款强大的 3D 模型运行时导入工具包,可以在游戏运行期间或编辑器中动态加载多种格式的模型,笔者也只是简单使用了从文件路径加载模型一种用法,旨在帮助你快速入门.

它支持的格式包括 FBX、OBJ、GLTF2、STL、PLY、3MF、DAE 和 ZIP 等,适用于多个平台,如 Windows、Mac、Linux、UWP、Android、iOS 和 WebGL。

主要功能:

动态模型导入:

支持从本地文件系统、网络 URL 或自定义数据源加载模型,无需依赖本地插件(完全用 C# 编写)。

开发者可以使用 AssetLoaderOptions 对加载过程进行详细配置。

材质、纹理和动画导入:

除了模型的几何信息外,还支持材质和纹理的自动映射,并能导入模型的动画。

跨平台支持:

能在多种平台上运行,包括桌面系统、移动设备和 WebGL。

自定义进度管理与回调:

TriLib 提供了一系列事件回调接口,例如在加载开始、加载进度更新、错误发生和加载完成时触发特定操作。

示例

官方示例

这是加载某个目录地址下的.obj模型示例,路径如下

核心方法

最核心的实际上就是这个方法来帮助我们加载来自文件的模型

其他的都是为了给该方法补齐参数的:如文件路径,加载选项(_assetLoaderOptions)

这里使用AssetLoader.CreateDefaultLoaderOptions创建默认的加载选项.

该方法的是异步加载,所以为我们提供了回调.

我主要介绍几个回调方法:

OnLoad:

当这个回调被执行的时候网格已经加载完了,这里回调提供我们一个加载上下文对象,

在这里我们才可以访问,这里这个对象的RootGameObject对象,就是我们想要的加载出来的对象.

注意是才,因为假设你的模型较大,如果你不是在这个回调中操作了这个对象,而是在其他位置(

AssetLoader.LoadModelFromFile会直接返回上下文对象,即便没加载完),且先于这个回调完成之前,那就会得到空引用异常.

OnMaterialsLoad:

这个显然是在Onload之后执行的一个回调,这里代表材质也被加载完毕了,整个加载过程完全结束,你可以安全的访问这个上下文中的模型对象,所以我建议在这里对模型对象进行处理.

加载过程结束并不需要你克隆,而是直接产生一个物体.

OnError:

发生加载错误的时候在这里处理,例如路径没有对应的模型

OnProgress:

这个回调在加载过程中会被不停地调用,传给你一个加载进度progress

progress加载完毕的时候会传递多次1.

全部代码

cs 复制代码
#pragma warning disable 649
using TriLibCore.General;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace TriLibCore.Samples
{
    /// <summary>
    /// Represents a sample that loads the "TriLibSample.obj" Model from the "Models" folder.
    /// </summary>
    public class LoadModelFromFileSample : MonoBehaviour
    {
        /// <summary>
        /// Returns the path to the "TriLibSample.obj" Model.
        /// </summary>
        private string ModelPath
        {
            get
            {
#if UNITY_EDITOR
                return $"{Application.dataPath}/TriLib/TriLibSamples/LoadModelFromFile/Models/TriLibSampleModel.obj";
#else
                return "Models/TriLibSampleModel.obj";
#endif
            }
        }

        /// <summary>
        /// Cached Asset Loader Options instance.
        /// </summary>
        private AssetLoaderOptions _assetLoaderOptions;

        AssetLoaderContext _assetLoaderContext;

        /// <summary>
        /// Loads the "Models/TriLibSample.obj" Model using the given AssetLoaderOptions.
        /// </summary>
        /// <remarks>
        /// You can create the AssetLoaderOptions by right clicking on the Assets Explorer and selecting "TriLib->Create->AssetLoaderOptions->Pre-Built AssetLoaderOptions".
        /// </remarks>
        private void Start()
        {
            if (_assetLoaderOptions == null)
            {
                _assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions(false, true);
            }

            _assetLoaderContext = AssetLoader.LoadModelFromFile(ModelPath, OnLoad, OnMaterialsLoad, OnProgress, OnError,
                null, _assetLoaderOptions);
          
        }
        

        /// <summary>
        /// Called when any error occurs.
        /// </summary>
        /// <param name="obj">The contextualized error, containing the original exception and the context passed to the method where the error was thrown.</param>
        private void OnError(IContextualizedError obj)
        {
            Debug.LogError($"An error occurred while loading your Model: {obj.GetInnerException()}");
        }

        /// <summary>
        /// Called when the Model loading progress changes.
        /// </summary>
        /// <param name="assetLoaderContext">The context used to load the Model.</param>
        /// <param name="progress">The loading progress.</param>
        private void OnProgress(AssetLoaderContext assetLoaderContext, float progress)
        {
            Debug.Log($"Loading Model. Progress: {progress:P}");
           
        }

        /// <summary>
        /// Called when the Model (including Textures and Materials) has been fully loaded.
        /// </summary>
        /// <remarks>The loaded GameObject is available on the assetLoaderContext.RootGameObject field.</remarks>
        /// <param name="assetLoaderContext">The context used to load the Model.</param>
        private void OnMaterialsLoad(AssetLoaderContext assetLoaderContext)
        {
            Debug.Log("Materials loaded. Model fully loaded.");
        }

        /// <summary>
        /// Called when the Model Meshes and hierarchy are loaded.
        /// </summary>
        /// <remarks>The loaded GameObject is available on the assetLoaderContext.RootGameObject field.</remarks>
        /// <param name="assetLoaderContext">The context used to load the Model.</param>
        private void OnLoad(AssetLoaderContext assetLoaderContext)
        {
            Debug.Log("网格加载完毕");
        }
    }
}
相关推荐
★YUI★16 小时前
学习游戏制作记录(玩家掉落系统,删除物品功能和独特物品)8.17
java·学习·游戏·unity·c#
SmalBox16 小时前
【渲染流水线】[光栅阶段]-[光栅插值]以UnityURP为例
unity·渲染
谷宇.16 小时前
【Unity3D实例-功能-拔枪】角色拔枪(二)分割上身和下身
游戏·unity·c#·游戏程序·unity3d·游戏开发·游戏编程
NRatel1 天前
亚马逊S3的使用简记(游戏资源发布更新)
游戏·unity·amazon s3
SmalBox2 天前
【渲染流水线】[几何阶段]-[屏幕映射]以UnityURP为例
unity·渲染
SmalBox3 天前
【渲染流水线】[几何阶段]-[归一化NDC]以UnityURP为例
unity·渲染
SmalBox3 天前
【渲染流水线】[几何阶段]-[图元装配]以UnityURP为例
unity·渲染
霜绛4 天前
Unity:GUI笔记(一)——文本、按钮、多选框和单选框、输入框和拖动条、图片绘制和框绘制
笔记·学习·unity·游戏引擎
谷宇.4 天前
【Unity3D实例-功能-移动】角色行走和奔跑的相互切换
游戏·unity·c#·unity3d·游戏开发·游戏编程
17岁的勇气4 天前
Unity Shader unity文档学习笔记(十九):粘土效果,任意网格转化成一个球(顶点动画,曲面着色器)
笔记·学习·unity·图形渲染·顶点着色器·曲面着色器