1. 程式人生 > >Unity簡易物件池(集合儲存資料)

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;
            }
        }
    }