[Unity游戏源码] Unity植物大战僵尸源代码

[复制链接]
查看644 | 回复0 | 2023-8-22 17:35:45 | 显示全部楼层 |阅读模式 来自 中国北京

例子脚本
可学习可二次开发 可以作为毕业设计

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

/// <summary>
/// 子弹对象池  仅作为简单讲解  不涉及其他复杂操作   单例
/// </summary>
public class BulletPool : MonoBehaviour
{

    public static BulletPool Instance;


    //子弹预制体
    public GameObject bulletPrefab;
    //对象池容量
    public int amount = 10;
    // 物品列表
    private List<GameObject> pool = new List<GameObject>();


    private void Awake()
    {
        Instance = this;
    }


    private void Start()
    {   //创建对象池的物体
        for (int i = 0; i < amount; i++)
        {
            GameObject go = Instantiate(bulletPrefab);
            //让物体失活
            go.SetActive(false);
            //添加到对象池
            pool.Add(go);

        }
    }

    //从对象池获取物体
    public GameObject GetPoolObject()
    {
        for (int i = 0; i < pool.Count; i++)
        {
            //找出未被激活的物体  将其激活  并返回
            if (!pool.activeInHierarchy)
            {
                pool.SetActive(true);
                return pool;
            }
        }
        //如果没有满足条件的物体  创建物体  添加到池中   激活 并返回
        GameObject go = GameObject.Instantiate(bulletPrefab);
        pool.Add(go);


        go.SetActive(true);
        return go;
    }
}



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则