using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameObjectPool : MonoBehaviour {
List<GameObject> pools = new List<GameObject>();//創(chuàng)建一個(gè)放object的List工具
private GameObjectPool() { }
private static GameObjectPool instance;
public static GameObjectPool Instance()
{
if (instance==null)
{
instance = new GameObject("GameObjectPool").AddComponent<GameObjectPool>();
}
return instance;
}
/// <summary>
/// 需要object在場(chǎng)景里顯示時(shí)
/// </summary>
/// <param obj="obj"></param>
/// <returns></returns>
public GameObject MyInstantiate(GameObject obj) {
//如果對(duì)象池為空,則實(shí)例化一個(gè)并返回
if (pools.Count == 0)
{
return Instantiate(obj, Vector3.zero, Quaternion.identity) as GameObject;
}
//對(duì)象池不為空 拿出索引為0的那個(gè) 并讓其顯示且移除對(duì)象池
else
{
GameObject obj2 = pools[0];//拿出索引為0的那個(gè)
obj2.SetActive(true);//讓其顯示
pools.Remove(obj2);//移除對(duì)象池
return obj2;//返回
}
}
/// <summary>
/// 對(duì)象不需要時(shí) 隱藏且放到對(duì)象池里
/// </summary>
/// <param obj="obj"></param>
public void MyDisable(GameObject obj) {
obj.SetActive(false);
pools.Add(obj);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public GameObject prefab;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
GameObjectPool.Instance().MyInstantiate(prefab);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour {
void OnEnable()
{
transform.position = Vector3.zero;
StartCoroutine(DelayDisable(3));
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate(Vector3.forward * Time.deltaTime * 20);
}
IEnumerator DelayDisable(float time) {
yield return new WaitForSeconds(time);
GameObjectPool.Instance().MyDisable(gameObject);
}
void OnDisable()
{
Debug.Log("自己消失掉");
}
}