Reference.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 引用计数类
  6. /// </summary>
  7. public class Reference
  8. {
  9. private List<Object> _requires;
  10. public int refCount;
  11. public virtual void AddReferance()
  12. {
  13. refCount++;
  14. }
  15. public virtual void Release()
  16. {
  17. refCount--;
  18. }
  19. /// <summary>
  20. /// 引用
  21. /// </summary>
  22. /// <param name="obj"></param>
  23. public void Require(Object obj)
  24. {
  25. if(_requires == null)
  26. {
  27. _requires = new List<Object>();
  28. _requires.Add(obj);
  29. AddReferance();
  30. }
  31. }
  32. /// <summary>
  33. /// 取消引用
  34. /// </summary>
  35. /// <param name="obj"></param>
  36. public void Dequire(Object obj)
  37. {
  38. if (_requires == null)
  39. return;
  40. if (_requires.Remove(obj))
  41. Release();
  42. }
  43. public bool IsUnused()
  44. {
  45. if(_requires != null)
  46. {
  47. for (var i = 0; i < _requires.Count; i++)
  48. {
  49. var item = _requires[i];
  50. if (item != null)
  51. continue;
  52. Release();
  53. _requires.RemoveAt(i);
  54. i--;
  55. }
  56. if (_requires.Count == 0)
  57. _requires = null;
  58. }
  59. return refCount <= 0;
  60. }
  61. }