AssetUnloader.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace TriLibCore
  4. {
  5. /// <summary>Represents a Class to destroy every Asset (Textures, Materials, Meshes) loaded by TriLib for this GameObject.</summary>
  6. public class AssetUnloader : MonoBehaviour
  7. {
  8. /// <summary>
  9. /// Assets Allocation List.
  10. /// </summary>
  11. public List<Object> Allocations;
  12. /// <summary>The Asset Unloader unique identifier.</summary>
  13. public int Id
  14. {
  15. get => _id;
  16. set
  17. {
  18. _id = value;
  19. Register();
  20. }
  21. }
  22. /// <summary>
  23. /// Custom data used to load the model.
  24. /// </summary>
  25. public object CustomData;
  26. [SerializeField]
  27. [HideInInspector]
  28. private int _id;
  29. private static int _lastId;
  30. private static readonly Dictionary<int, int> AssetUnloaders = new Dictionary<int, int>();
  31. /// <summary>Gets the next allocation Identifier.</summary>
  32. /// <returns>The Allocation Identifier.</returns>
  33. public static int GetNextId()
  34. {
  35. return _lastId++;
  36. }
  37. /// <summary>
  38. /// Returns whether there is any AssetUnloader instance active.
  39. /// </summary>
  40. public static bool HasRegisteredUnloaders
  41. {
  42. get
  43. {
  44. return AssetUnloaders.Count > 0;
  45. }
  46. }
  47. private void Register()
  48. {
  49. if (!AssetUnloaders.ContainsKey(_id))
  50. {
  51. AssetUnloaders[_id] = 0;
  52. }
  53. else
  54. {
  55. AssetUnloaders[_id]++;
  56. }
  57. }
  58. private void Start()
  59. {
  60. Register();
  61. }
  62. private void OnDestroy()
  63. {
  64. if (AssetUnloaders.TryGetValue(_id, out var value))
  65. {
  66. if (--value <= 0)
  67. {
  68. for (var i = 0; i < Allocations.Count; i++)
  69. {
  70. var allocation = Allocations[i];
  71. if (allocation == null)
  72. {
  73. continue;
  74. }
  75. Destroy(allocation);
  76. }
  77. AssetUnloaders.Remove(_id);
  78. }
  79. else
  80. {
  81. AssetUnloaders[_id] = value;
  82. }
  83. }
  84. }
  85. }
  86. }