Unity简单对象池Pool

第一步:创建2个脚步,如图

Unity简单对象池Pool

代码如下:

Pool脚本

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

public class pool : MonoBehaviour {
    public GameObject goPrefabs;
    //对象池子
    private List<GameObject> listpool = new List<GameObject>();
    //池子里面的物体个数
    public int poolCount = 10;

    //给池子添加物体
    public void push(GameObject go)
    {
        //如果小与池子中元素的个数
        if(listpool.Count<poolCount)
        {
            //每次都让创建的物体回到原来位置
            go.transform.position = goPrefabs.transform.position;
            listpool.Add(go);
        }
        else
        {
            //多了就摧毁
            Destroy(go);
        }
    }
    //将池子物体移除
    public GameObject pop()
    {
        if(listpool.Count>0)
        {
            GameObject go = listpool[0]; 
            listpool.Remove(listpool[0]);
            return go;
        }
        else
        {
            //如果没有物体就生成预制体
            return Instantiate(goPrefabs);
        }
    }
    public void removeList()
    {
        listpool.Clear();
    }
}

 Text脚本

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

public class text : MonoBehaviour {
    //管理存在的对象
    private List<GameObject> list = new List<GameObject>();
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetMouseButtonDown(0))
        {
            //从对象池中拿出物体
            GameObject go = GetComponent<pool>().pop();
            //添加到外部管理中
            list.Add(go);
            //下次从池子中提取就直接显示出来
            go.SetActive(true);
            Debug.Log("左键");
        }
        if(Input.GetMouseButtonDown(1))
        {
            if(list.Count>0)
            {
               //将外部管理的物体添加到池子中,多于的就摧毁
                GetComponent<pool>().push(list[0]);
                //遍历到的就隐藏
                list[0].SetActive(false);
                list.Remove(list[0]);
            }
        }
	}
}

第二步:创建一个cube,添加move脚步

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

public class move : MonoBehaviour {

    private Vector3 pos;
    private float t1;
	// Use this for initialization
	void Start () {
        pos = new Vector3(10, 0, 0);
	}
	
	// Update is called once per frame
	void Update () {
        t1 += 0.1f* Time.deltaTime;
        transform.position = Vector3.Lerp(transform.position, pos,t1);
    }
    void OnEnable()
    {
        t1 = 0;
    }
}

代码实现下就成功了