0

I created an event in the button when pressed, put there the Shoot function from the code below. When appearing on the scene, the object that should shoot bullets initializes them, but at the press of a button does not make them active, but if you initialize when pressing the button, then makes them visible, but with each time creates bullets there are more and more.

Why pressing the button doesn't make the bullets created in Start() active?

Edit: I forgot to mention, i'm using Photon, i edit script with PhotonNetwork. part, but still have an issue with activating object.

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

ObjectPool code:

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 = PhotonNetwork.Instantiate(prefab.name, 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;
    }
}
Rollis
  • 93
  • 8

0 Answers0