using TriLibCore.General; using UnityEngine; using TriLibCore.Extensions; using UnityEngine.UI; namespace TriLibCore.Samples { /// /// Represents a sample that loads a Model from a file-picker. /// public class LoadModelFromFilePickerSample : MonoBehaviour { /// /// The last loaded GameObject. /// private GameObject _loadedGameObject; /// /// The load model Button. /// [SerializeField] private Button _loadModelButton; /// /// Creates the AssetLoaderOptions instance and displays the Model file-picker. /// /// /// You can create the AssetLoaderOptions by right clicking on the Assets Explorer and selecting "TriLib->Create->AssetLoaderOptions->Pre-Built AssetLoaderOptions". /// public void LoadModel() { var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions(); var assetLoaderFilePicker = AssetLoaderFilePicker.Create(); assetLoaderFilePicker.LoadModelFromFilePickerAsync("Select a Model file", OnLoad, OnMaterialsLoad, OnProgress, OnBeginLoad, OnError, null, assetLoaderOptions); } /// /// Called when the the Model begins to load. /// /// Indicates if any file has been selected. private void OnBeginLoad(bool filesSelected) { _loadModelButton.interactable = false; } /// /// Called when any error occurs. /// /// The contextualized error, containing the original exception and the context passed to the method where the error was thrown. private void OnError(IContextualizedError obj) { Debug.LogError($"An error ocurred while loading your Model: {obj.GetInnerException()}"); } /// /// Called when the Model loading progress changes. /// /// The context used to load the Model. /// The loading progress. private void OnProgress(AssetLoaderContext assetLoaderContext, float progress) { Debug.Log($"Loading Model. Progress: {progress:P}"); } /// /// Called when the Model (including Textures and Materials) has been fully loaded, or after any error occurs. /// /// The loaded GameObject is available on the assetLoaderContext.RootGameObject field. /// The context used to load the Model. private void OnMaterialsLoad(AssetLoaderContext assetLoaderContext) { if (assetLoaderContext.RootGameObject != null) { Debug.Log("Materials loaded. Model fully loaded."); } else { Debug.Log("Model could not be loaded."); } } /// /// Called when the Model Meshes and hierarchy are loaded. /// /// The loaded GameObject is available on the assetLoaderContext.RootGameObject field. /// The context used to load the Model. private void OnLoad(AssetLoaderContext assetLoaderContext) { if (_loadedGameObject != null) { Destroy(_loadedGameObject); } _loadedGameObject = assetLoaderContext.RootGameObject; if (_loadedGameObject != null) { Camera.main.FitToBounds(assetLoaderContext.RootGameObject, 2f); Debug.Log("Model loaded. Loading materials."); } else { Debug.Log("Model materials could not be loaded."); } _loadModelButton.interactable = true; } } }