Unity 学习笔记

Unity 对象池实现方案:

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

public class ObjectPool : MonoBehaviour
{

    private List _objectList;
    private GameObject _objectToRecycle;
    private int _defaultPoolSize = 5;

    private static Dictionary _pool = new Dictionary();

    private void Init()
    {
        _objectList = new List(_defaultPoolSize);
        for (int i = 0; i < _defaultPoolSize; i++)
        {
            GameObject go = Instantiate(_objectToRecycle);
            go.transform.SetParent(transform);
            go.SetActive(false);
            _objectList.Add(go);
        }
    }

    private GameObject PoolObject(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
    {
        GameObject freeObject = (from item in _objectList
                                 where item.activeSelf == false
                                 select item
        ).FirstOrDefault();

        if (freeObject == null)
        {
            freeObject = Instantiate(_objectToRecycle, position, rotation);
            freeObject.transform.SetParent(transform);
            _objectList.Add(freeObject);
        }
        else
        {
            freeObject.transform.position = position;
            freeObject.transform.rotation = rotation;
            freeObject.SetActive(true);
        }
        return freeObject;
    }
    public static void InitPool(GameObject original, int poolsize = 5)
    {

        int _originalID = original.GetInstanceID();
        if (!_pool.ContainsKey(_originalID))
        {
            GameObject objectPoolGameObject = new GameObject("ObjectPool:" + original.name);
            ObjectPool objPool = objectPoolGameObject.AddComponent();
            objPool._objectToRecycle = original;
            objPool._defaultPoolSize = poolsize;
            objPool.Init();
            _pool.Add(_originalID, objPool);
        }
    }
    public static GameObject GetInstance(int originalID, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
    {
        return _pool[originalID].PoolObject(position, rotation);
    }
    public static GameObject GetInstance(GameObject original, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
    {
        int id = original.GetInstanceID();
        InitPool(original);
        return _pool[id].PoolObject(position, rotation);
    }

    public void Release(GameObject obj)
    {
        obj.SetActive(false);
    }
}

你可能感兴趣的:(Unity 学习笔记)