按下按钮不会从 ObjectPool 中创建对象

问题描述 投票:0回答:0

我在按下按钮时创建了一个事件,将下面代码中的

Shoot
功能放在那里。当出现在场景中时,应该发射子弹的对象会初始化它们,但在按下按钮时不会使它们处于活动状态,但是如果在按下按钮时进行初始化,则会使它们可见,但每次都会创建子弹越来越多。

为什么按下按钮不会使

Start()
中创建的子弹激活?

using UnityEngine;

public class PlayerShooter : ObjectPool
{
    [SerializeField] 
    private GameObject _bullet;

    private void Start()
    {
        Initialize(_bullet);
    }

    public void Shoot()
    {
        // Initialize(_bullet);
        if (TryGetObject(out GameObject bullet))
        {
            bullet.SetActive(true);
        }
    }
}

对象池代码:

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

public class ObjectPool : MonoBehaviour
{
    [SerializeField] 
    private int _amount;

    private List<GameObject> _pool = new();

    protected void Initialize(GameObject prefab)
    {
        for (int i = 0; i < _amount; i++)
        {
            GameObject spawned = Instantiate(prefab, transform.position, Quaternion.identity);
            spawned.SetActive(false);
            _pool.Add(spawned);
        }
    }

    protected bool TryGetObject(out GameObject result)
    {
        result = _pool.FirstOrDefault(gameObject => gameObject.activeSelf == false);
        return result != null;
    }
}
c# unity3d objectpool
© www.soinside.com 2019 - 2024. All rights reserved.