yyl
2025-06-09 d68f2c0be6edf436b6033773147588b7574a93b0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.Collections.Generic;
using System;
using UnityEngine;
 
public class ObjectPool<T>
{
    /// <summary>
    /// 池的堆栈
    /// </summary>
    private readonly Stack<T> m_Inactived = new Stack<T>();
 
    /// <summary>
    /// 池对象总数,包括已激活和未激活
    /// </summary>
    public int totalCount;
 
    /// <summary>
    /// 取得当前还有多少激活对象
    /// </summary>
    public int activedCount
    {
        get
        {
            return totalCount - inactivedCount;
        }
    }
 
    /// <summary>
    /// 取得池里还有多少对象
    /// </summary>
    public int inactivedCount
    {
        get
        {
            return m_Inactived.Count;
        }
    }
 
    private Action<T> m_OnObjectGet;// 供外部传入的回调方法,在获取对象的时候对该对象进行一些可能是初始化的操作
    private Action<T> m_OnObjectRelease;// 供外部传入的回调方法,在释放对象的时候对该对象进行一些可能是重置的操作
 
    public ObjectPool(Action<T> onGetAction, Action<T> onReleaseAction)
    {
        m_OnObjectGet = onGetAction;
        m_OnObjectRelease = onReleaseAction;
    }
 
    public void Add(T element)
    {
        m_Inactived.Push(element);
        totalCount++;
    }
 
    public T Get()
    {
        T element;
        // 错误保护
        if (inactivedCount == 0)
        {
            Debug.LogWarningFormat("获取池对象时,池已经为空.");
            return default(T);
        }
        // 取得池对象
        element = m_Inactived.Pop();
        // 执行获取逻辑
        if (m_OnObjectGet != null)
        {
            m_OnObjectGet(element);
        }
        return element;
    }
 
    public void Release(T element)
    {
        // 错误保护
        if (inactivedCount > 0 && ReferenceEquals(element, m_Inactived.Peek()))
        {
            Debug.LogWarningFormat("向池释放对象的时候发现,该对象已经被释放了.", element.ToString());
            return;
        }
        // 执行外部传入的释放逻辑
        if (m_OnObjectRelease != null)
        {
            m_OnObjectRelease(element);
        }
        m_Inactived.Push(element);
    }
 
    public void Clear()
    {
        m_Inactived.Clear();
    }
}