| | 1 | | using DCL; |
| | 2 | | using UnityEngine; |
| | 3 | |
|
| | 4 | | public class DynamicOBJLoaderController : MonoBehaviour |
| | 5 | | { |
| 1 | 6 | | public bool loadOnStart = true; |
| 1 | 7 | | public string OBJUrl = ""; |
| | 8 | | public GameObject loadingPlaceholder; |
| | 9 | |
|
| | 10 | | public event System.Action OnFinishedLoadingAsset; |
| | 11 | |
|
| | 12 | | [HideInInspector] public bool alreadyLoadedAsset = false; |
| | 13 | | [HideInInspector] public GameObject loadedOBJGameObject; |
| | 14 | |
|
| | 15 | | IWebRequestAsyncOperation asyncOp = null; |
| | 16 | |
|
| | 17 | | void Awake() |
| | 18 | | { |
| 1 | 19 | | if (loadOnStart && !string.IsNullOrEmpty(OBJUrl)) |
| | 20 | | { |
| 0 | 21 | | LoadAsset(); |
| | 22 | | } |
| 1 | 23 | | } |
| | 24 | |
|
| | 25 | | public void LoadAsset(string url = "", bool loadEvenIfAlreadyLoaded = false) |
| | 26 | | { |
| 1 | 27 | | if (alreadyLoadedAsset && !loadEvenIfAlreadyLoaded) |
| 0 | 28 | | return; |
| | 29 | |
|
| 1 | 30 | | if (!string.IsNullOrEmpty(url)) |
| | 31 | | { |
| 1 | 32 | | OBJUrl = url; |
| | 33 | | } |
| | 34 | |
|
| 1 | 35 | | if (asyncOp != null) |
| | 36 | | { |
| 0 | 37 | | asyncOp.Dispose(); |
| | 38 | | } |
| | 39 | |
|
| 1 | 40 | | LoadAsset(); |
| 1 | 41 | | } |
| | 42 | |
|
| | 43 | | void LoadAsset() |
| | 44 | | { |
| 1 | 45 | | if (!string.IsNullOrEmpty(OBJUrl)) |
| | 46 | | { |
| 1 | 47 | | Destroy(loadedOBJGameObject); |
| | 48 | |
|
| 1 | 49 | | asyncOp = Environment.i.platform.webRequest.Get( |
| | 50 | | url: OBJUrl, |
| | 51 | | OnSuccess: (webRequestResult) => |
| | 52 | | { |
| 1 | 53 | | loadedOBJGameObject = OBJLoader.LoadOBJFile(webRequestResult.webRequest.downloadHandler.text, true); |
| 1 | 54 | | loadedOBJGameObject.name = "LoadedOBJ"; |
| 1 | 55 | | loadedOBJGameObject.transform.SetParent(transform); |
| 1 | 56 | | loadedOBJGameObject.transform.localPosition = Vector3.zero; |
| | 57 | |
|
| 1 | 58 | | OnFinishedLoadingAsset?.Invoke(); |
| 1 | 59 | | alreadyLoadedAsset = true; |
| 1 | 60 | | }, |
| | 61 | | OnFail: (webRequestResult) => |
| | 62 | | { |
| 0 | 63 | | Debug.Log("Couldn't get OBJ, error: " + webRequestResult.webRequest.error + " ... " + OBJUrl); |
| 0 | 64 | | }); |
| 1 | 65 | | } |
| | 66 | | else |
| | 67 | | { |
| 0 | 68 | | Debug.Log("couldn't load OBJ because url is empty"); |
| | 69 | | } |
| | 70 | |
|
| 1 | 71 | | if (loadingPlaceholder != null) |
| | 72 | | { |
| 0 | 73 | | loadingPlaceholder.SetActive(false); |
| | 74 | | } |
| 1 | 75 | | } |
| | 76 | |
|
| | 77 | | void OnDestroy() |
| | 78 | | { |
| 1 | 79 | | if (asyncOp != null) |
| | 80 | | { |
| 1 | 81 | | asyncOp.Dispose(); |
| | 82 | | } |
| | 83 | |
|
| 1 | 84 | | Destroy(loadingPlaceholder); |
| 1 | 85 | | Destroy(loadedOBJGameObject); |
| 1 | 86 | | } |
| | 87 | | } |