当先锋百科网

首页 1 2 3 4 5 6 7

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 = ;
    public GameObject prefab;//要克隆的对象
    public bool isLimit = false;  //是否限制 无限克隆
    public static GameObjectPoolCon _Instance;
    private void Awake()
    {
        _Instance = this;
        for (int i = ; i < count; i++)
        {
            GameObject go = Instantiate(prefab);
            go.SetActive(false);
            objList.Add(go);//把初始化出来的对象 设置为不可见并且存放到 list列表中
        }

    }
    public GameObject CreateObj()
    {

        for (int i = ; i < objList.Count; i++)
        {
            int index = (currentIndex + i) % objList.Count;//保证index 不会超出索引
            if (!objList[index].activeInHierarchy)
            {
                currentIndex = (index + ) % 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))
        {
            go = GameObjectPool._Instance.CreateObj();
            if (go != null)
            {
                go.SetActive(true);
                go.transform.position = oriPos.position;
                go.GetComponent<Rigidbody>().velocity = Vector3.one;
            }
        }
    }