123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- namespace HyperlinkText
- {
- public class ObjectPool<T> where T : new()
- {
- public ObjectPool(Action<T> onGet, Action<T> onRelease)
- {
- this.m_OnGet = onGet;
- this.m_OnRelease = onRelease;
- }
- public int CountAll { get; set; }
- public int CountActive
- {
- get
- {
- return this.CountAll - this.CountInactive;
- }
- }
- public int CountInactive
- {
- get
- {
- return this.m_Stack.Count;
- }
- }
- public T Get()
- {
- T t;
- if (this.m_Stack.Count == 0)
- {
- t = Activator.CreateInstance<T>();
- this.CountAll++;
- }
- else
- {
- t = this.m_Stack.Pop();
- }
- if (this.m_OnGet != null)
- {
- this.m_OnGet(t);
- }
- return t;
- }
- public void Release(T item)
- {
- if (this.m_Stack.Count > 0)
- {
- T t = this.m_Stack.Peek();
- if (t.Equals(item))
- {
- Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
- }
- }
- if (this.m_OnRelease != null)
- {
- this.m_OnRelease(item);
- }
- this.m_Stack.Push(item);
- }
- private readonly Stack<T> m_Stack = new Stack<T>();
- private readonly Action<T> m_OnGet;
- private readonly Action<T> m_OnRelease;
- }
- }
|