自己實(shí)現(xiàn)一個(gè)對(duì)象池

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("自己消失掉");
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容