Unity简易对象池(集合存储数据)

1、下面这个代码是用list集合创建的简易对象池,只能存储一种游戏对象。

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

public class GameObjectPool : MonoBehaviour
{
    public List<GameObject> objList = new List<GameObject>();
    public int count;//初始化场景中有几个对象
    public int currentIndex = 0;
    public GameObject prefab;//要克隆的对象
    public bool isLimit = false;  //是否限制 无限克隆
    public static GameObjectPoolCon _Instance;
    private void Awake()
    {
        _Instance = this;
        for (int i = 0; i < count; i++)
        {
            GameObject go = Instantiate(prefab);
            go.SetActive(false);
            objList.Add(go);//把初始化出来的对象 设置为不可见并且存放到 list列表中
        }

    }
    public GameObject CreateObj()
    {

        for (int i = 0; i < objList.Count; i++)
        {
            int index = (currentIndex + i) % objList.Count;//保证index 不会超出索引
            if (!objList[index].activeInHierarchy)
            {
                currentIndex = (index + 1) % objList.Count;
                return objList[index];
            }
        }
        if (!isLimit)
        {
            GameObject go = Instantiate(prefab);
           // go.SetActive(false);//不在设置为不可见 ,因为即刻就要用
            objList.Add(go);
            return go;
        }
        return null;
    }
}

2、下面的代码是从对象池中调用游戏对象。此代码适合用到射击游戏中

 public Transform oriPos;//每次重新赋予新的位置
    GameObject go;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            go = GameObjectPool._Instance.CreateObj();
            if (go != null)
            {
                go.SetActive(true);
                go.transform.position = oriPos.position;
                go.GetComponent<Rigidbody>().velocity = Vector3.one;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_43109909/article/details/82562160