using System.Collections;
using System.Collections.Generic;
public class GameObjectPool : MonoBehaviour {
List<GameObject> pools = new List<GameObject>();
private GameObjectPool(){}
private static GameObjectPool instance;
public static GameObjectPool GetInstance()
{
if (instance==null)
{
instance = new GameObject("GameObjectPool").AddComponent<GameObjectPool>();
}
return instance;
}
//获取一个对象
public GameObject MyInstantiate(GameObject name)
{
if (pools.Count==0)
{
return Instantiate(name, Vector3.zero, Quaternion.identity) as GameObject;
}
//取出一个对象
else
{
GameObject obj = pools[0];
obj.SetActive(true);
//将被取出的元素
pools.Remove(obj);
return obj;
}
}
//存取一个对象
public void MyDisable(GameObject name)
{
name.SetActive(false);
pools.Add(name);
}
}
using UnityEngine;
using System.Collections;
public class gameManager : MonoBehaviour {
public GameObject obj;
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
GameObjectPool.GetInstance().MyInstantiate(obj);
}
}
}
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
void OnEnable()
{
//如果不加这句代码,从对象池中取出的子弹就会从上一次消失的位置开始运动。而不是你设定的子弹生成位置
transform.position = Vector3.zero;
//开启协程方法
StartCoroutine(DelayDisable(3f));
}
void Update()
{
//子弹生成,自动向前运动
transform.Translate(Vector3.forward * Time.deltaTime * 20);
}
void OnDisable()
{
Debug.Log("I'm over");
}
//子弹消失的方法
IEnumerator DelayDisable(float time)
{
//等待三秒
yield return new WaitForSeconds(time);
//调用单例中向对象池里面存对象的方法
GameObjectPool.GetInstance().MyDisable(gameObject);
}
}