对象池简单实现

1、对象池

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

public class GameObjectPool : MonoBehaviour
{
    public GameObject prefab;
    public int maxPoolSize = 100;
    private Queue<GameObject> pool = new Queue<GameObject>();
    void Start()
    {
        this.EnLargePool();
    }
    private void EnLargePool()
    {
        for (int i = 0; i < maxPoolSize; i++)
        {
            GameObject obj = Instantiate(prefab, transform);
            pool.Enqueue(obj);
            obj.SetActive(false);
        }
    }
    public GameObject GetObj()
    {
        if (pool.Count==0)
        {
            this.EnLargePool();
        }
        GameObject obj =  pool.Dequeue();
        obj.SetActive(true);
        return obj;
    }
    public void ReturnObj(GameObject obj)
    {
        pool.Enqueue(obj);
        obj.SetActive(false);

    }
}

2、发生器

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

public class Generator : MonoBehaviour
{
    // Start is called before the first frame update

    private GameObjectPool pool;
    public GameObject poolPrefab;
    float spawnTimer = 0f;
    public float spawnInterval = 1f;
    void Start()
    {
        pool = poolPrefab.GetComponent<GameObjectPool>();
    }

    // Update is called once per frame
    void Update()
    {
        spawnTimer += Time.deltaTime;
        if(spawnTimer>= spawnInterval)
        {
            spawnTimer = 0;
            GameObject prefab = pool.GetObj();
            prefab.GetComponent<Renderer>().material.color= Color.red;
            prefab.transform.position = this.transform.position;
           
        }
    }

 
}

3、收集器

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

public class Collection : MonoBehaviour
{
    private GameObjectPool pool;
    public GameObject poolPrefab;
    // Start is called before the first frame update
    void Start()
    {
        pool = poolPrefab.GetComponent<GameObjectPool>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnCollisionEnter(Collision collision)
    {
        pool.ReturnObj(collision.gameObject);
    }
}

适当调整对象池的容量,来防止多次扩容和产生GC问题。
对象池简单实现_第1张图片

你可能感兴趣的:(unity,c#,开发语言)