AssetUnloader.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. private int _id;
  13. /// <summary>The Asset Unloader unique identifier.</summary>
  14. public int Id
  15. {
  16. get => _id;
  17. set
  18. {
  19. _id = value;
  20. Register();
  21. }
  22. }
  23. private static int _lastId;
  24. private static readonly Dictionary<int, int> AssetUnloaders = new Dictionary<int, int>();
  25. /// <summary>Gets the next allocation Identifier.</summary>
  26. /// <returns>The Allocation Identifier.</returns>
  27. public static int GetNextId()
  28. {
  29. return _lastId++;
  30. }
  31. private void Register()
  32. {
  33. if (!AssetUnloaders.ContainsKey(_id))
  34. {
  35. AssetUnloaders[_id] = 0;
  36. }
  37. else
  38. {
  39. AssetUnloaders[_id]++;
  40. }
  41. }
  42. private void Start()
  43. {
  44. Register();
  45. }
  46. private void OnDestroy()
  47. {
  48. if (AssetUnloaders.TryGetValue(_id, out var value))
  49. {
  50. if (--value <= 0)
  51. {
  52. foreach (var allocation in Allocations)
  53. {
  54. if (allocation == null)
  55. {
  56. continue;
  57. }
  58. Destroy(allocation);
  59. }
  60. AssetUnloaders.Remove(_id);
  61. }
  62. else
  63. {
  64. AssetUnloaders[_id] = value;
  65. }
  66. }
  67. }
  68. }
  69. }