一、对象池
在一款游戏中,我们不止有一个对象池,为了方便对对象池的创建,由此写了一个模板类。当然,也可以实现全功能的对象池,不管什么类型都可以。在此就不在阐述了。
在此模板类中,使用了委托,系统自带的委托函数,以及堆栈的使用。
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine;
public class ObjectPool<T> where T : new()
{
//最好改为只读的
private Stack<T> m_Stack = new Stack<T>(); //使用栈进行创建。
private UnityAction<T> m_ActionOnGet;
private UnityAction<T> m_ActionOnRelease;
public int countAll { get; private set; } //池中对象的总个数
public int countActive { get { return countAll - countInactive; } } //活跃的对象
public int countInactive { get { return m_Stack.Count; } } //失活的对象,即可以进行回收的对象
public T CreateObject()
{
T element;
if (m_Stack.Count == 0)
{
element = new T();
countAll++;
}
else
{
element = m_Stack.Pop();
}
if (m_ActionOnGet != null)
m_ActionOnGet(element);
return element;
}
public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
{
m_ActionOnGet = actionOnGet;
m_ActionOnRelease = actionOnRelease;
}
public void Release(T element)
{
if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
//输出错误日志,可以使用自己写的日志进行输出
Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
if (m_ActionOnRelease != null)
m_ActionOnRelease(element);
m_Stack.Push(element); //弹栈
}
}
二、C#手动回收
在Net中,由GC垃圾回收线程掌握对象资源的释放,程序员无法掌控析构函数的调用时机。对于一些非托管资源,比如数据库链接对象等,需要实现IDisposable接口进行手动的垃圾回收。
在此模板类中,使用了委托,系统自带的委托函数,以及堆栈的使用。
//
// 摘要:
// Defines a method to release allocated resources.
[ComVisible(true)]
public interface IDisposable
{
//
// 摘要:
// Performs application-defined tasks associated with freeing, releasing, or resetting
// unmanaged resources.
void Dispose();
}