using System; using Models.Interferences; using UnityEngine; using UnityEngine.Networking; using System.Collections; using System.IO; using Helpers; using Models; public class ResourceProvider : MonoBehaviour { // Load an extra layout resource public IEnumerator LoadResource(Resource resource, Action callback) { yield return LoadResource(resource, resource.assetBundle, resource.prefabName, callback); } public IEnumerator LoadResource(AnimatedInterference interference, Action callback) { yield return LoadResource(interference, interference.assetBundle, interference.prefabName, callback); } /// /// Asynchronously load asset bundles and store them in the scene. /// /// A resource object on which the loading state will be set /// Path to the asset bundle /// Name of the prefab to load /// Callback to execute once the resource is fully loaded and instantiated /// private IEnumerator LoadResource(ILoadableResource resource, string assetBundle, string prefabName, Action callback) { // Create a web request to the asset bundle. This bundle can be online or locally stored var path = ResourceHelper.GetPath(assetBundle, ResourceHelper.Type.AssetBundles); using var www = UnityWebRequestAssetBundle.GetAssetBundle(path); yield return www.SendWebRequest(); // Only accept success if (www.result != UnityWebRequest.Result.Success) { Debug.LogError(www.error); resource.SetLoadingState(ResourceLoadingState.Error); yield break; } // Download the GameObject and create a new instance inside the scene var bundle = DownloadHandlerAssetBundle.GetContent(www); var prefab = bundle.LoadAsset(prefabName); if (prefab is null) { // unload the AssetBundle in case the prefab does not exist bundle.Unload(false); Debug.LogError($"The prefab {prefabName} cannot be found in bundle {assetBundle}"); resource.SetLoadingState(ResourceLoadingState.Error); yield break; } var go = Instantiate(prefab, transform.parent); // unload the AssetBundle data instantly bundle.Unload(false); // Make sure the object has been initialized if (go is null) { Debug.LogError($"GameObject from {assetBundle} is null"); resource.SetLoadingState(ResourceLoadingState.Error); yield break; } // make sure the animator of the object is disabled, if any var animator = go.GetComponent(); if (animator != null) { animator.enabled = false; } try { callback(go); resource.SetLoadingState(ResourceLoadingState.Loaded); } catch (InvalidDataException e) { resource.SetLoadingState(ResourceLoadingState.Error); } } }