AssetUnloader.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. ChangeLayerRecursively(transform);
  46. }
  47. public void ChangeLayerRecursively(Transform parentTransform)
  48. {
  49. // 修改父物体的层级
  50. parentTransform.gameObject.layer = LayerMask.NameToLayer("Arrow");
  51. // 遍历所有子物体,并递归调用ChangeLayerRecursively方法
  52. for (int i = 0; i < parentTransform.childCount; i++)
  53. {
  54. Transform childTransform = parentTransform.GetChild(i);
  55. ChangeLayerRecursively(childTransform);
  56. }
  57. }
  58. private void OnDestroy()
  59. {
  60. if (AssetUnloaders.TryGetValue(_id, out var value))
  61. {
  62. if (--value <= 0)
  63. {
  64. foreach (var allocation in Allocations)
  65. {
  66. if (allocation == null)
  67. {
  68. continue;
  69. }
  70. Destroy(allocation);
  71. }
  72. AssetUnloaders.Remove(_id);
  73. }
  74. else
  75. {
  76. AssetUnloaders[_id] = value;
  77. }
  78. }
  79. }
  80. }
  81. }