unity 游戏对象池

对象池 :用在量大,重复利用高的地方。

代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public interface IRecycleable
{
    //回收关闭
    void OnRecycle();
    //重启
	void OnReuse();
}

//泛型对象池
public class ObjectPool<T> where T : IRecycleable
{
	
	int size;
   //容器
    Queue<T> container;
   //放入对象池的GameObject 元素
	GameObject moudle;

	private static ObjectPool<T> _self;
	public static ObjectPool<T> GameInstance
	{
		get
		{
			if (_self == null)
				Debug.LogError ("This pool NOT Created yet");
			return _self;
		}
	}

    //设置对象池大小 和初始容量
	public ObjectPool (int srcSize , GameObject _moudle)
	{
		container = new Queue<T> ();
		size = srcSize;
		moudle = _moudle;
		for(int i = 0; i < srcSize; i++)
		{
			GameObject obj = GameObject.Instantiate (moudle) as GameObject;
			T temp = obj.GetComponent<T> ();
			if (temp == null) 
			{
				Debug.LogError ("The GameObject Can't Recycle");
				break;
			}
			temp.OnRecycle ();
			container.Enqueue (temp);
		}
	}
  


    //对象池元素
	public T GetObjectFromPool()
	{
		if(container.Count == 0)
		{
			GameObject obj = GameObject.Instantiate (moudle) as GameObject;
			T temp = obj.GetComponent<T> ();
			container.Enqueue (temp);
		}
		T r = container.Dequeue ();
		r.OnReuse ();
		return r;
	}

    //回收和向对象池添加元素
	public void Recycle(GameObject obj)
	{
		T temp = obj.GetComponent<T> ();
		IRecycleable r = (IRecycleable)temp;
		r.OnRecycle ();
		container.Enqueue (temp);
	}
}

对象池使用:

列代码:

//创建hudController对象池,资源为resources.load加载

GameObject obj = Resources.Load<GameObject>("HUD");
        hudPool = new ObjectPool<HUDController> (5, obj);

//重对象池中获取一个特定类型的的对象

HUDController h = hudPool.GetObjectFromPool ();

//使用完后回收到对象池

hudPool.Recycle (h.gameObject);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值