自己实现一个对象池

2017-05-17  本文已影响0人  HMY轩园
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("自己消失掉");
    }

}
上一篇下一篇

猜你喜欢

热点阅读