自己實現一個對象池

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

public class GameObjectPool : MonoBehaviour {

    List<GameObject> pools = new List<GameObject>();//創建一個放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在場景里顯示時
    /// </summary>
    /// <param obj="obj"></param>
    /// <returns></returns>
    public GameObject MyInstantiate(GameObject  obj) {
        //如果對象池為空,則實例化一個并返回
        if (pools.Count == 0)
        {
            return Instantiate(obj, Vector3.zero, Quaternion.identity) as GameObject;
        }
        //對象池不為空 拿出索引為0的那個 并讓其顯示且移除對象池
        else
        {
            GameObject obj2 = pools[0];//拿出索引為0的那個
            obj2.SetActive(true);//讓其顯示
            pools.Remove(obj2);//移除對象池
            return obj2;//返回
        }
    }
    /// <summary>
    /// 對象不需要時 隱藏且放到對象池里
    /// </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("自己消失掉");
    }

}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容