2021년 4학년 1학기 기업연계프로젝트2 컴퓨터소프트웨어공학과 <원광투어팀> 팀장 : 송유진 팀원 : 김나영, 이경희, 한유진
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.8 KiB

5 years ago
  1. //========= Copyright 2016-2020, HTC Corporation. All rights reserved. ===========
  2. using System;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Events;
  6. namespace HTC.UnityPlugin.Utility
  7. {
  8. public class ObjectPool<T>
  9. {
  10. private readonly Stack<T> stack = new Stack<T>();
  11. private readonly Func<T> actionOnNew;
  12. private readonly UnityAction<T> actionOnGet;
  13. private readonly UnityAction<T> actionOnRelease;
  14. public int CountAll { get; private set; }
  15. public int CountInactive { get { return stack.Count; } }
  16. public int CountActive { get { return CountAll - CountInactive; } }
  17. public ObjectPool(Func<T> onNew, UnityAction<T> onGet = null, UnityAction<T> onRelease = null)
  18. {
  19. actionOnNew = onNew;
  20. actionOnGet = onGet;
  21. actionOnRelease = onRelease;
  22. }
  23. public T Get()
  24. {
  25. T element;
  26. if (stack.Count == 0)
  27. {
  28. element = actionOnNew == null ? default(T) : actionOnNew.Invoke();
  29. CountAll++;
  30. }
  31. else
  32. {
  33. element = stack.Pop();
  34. }
  35. if (actionOnGet != null) { actionOnGet.Invoke(element); }
  36. return element;
  37. }
  38. public void Release(T element)
  39. {
  40. if (stack.Count > 0 && ReferenceEquals(stack.Peek(), element))
  41. {
  42. Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
  43. }
  44. if (actionOnRelease != null) { actionOnRelease.Invoke(element); }
  45. stack.Push(element);
  46. if (stack.Count > CountAll)
  47. {
  48. CountAll = stack.Count;
  49. }
  50. }
  51. }
  52. }