Error: When bullets are being instantiated, I can shoot bullet, but when they all have instantiated, I can’t shoot/ use these bullets again.
bullet Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scriptBullet : MonoBehaviour
{
public GameObject bullet;
public float maxDistance;
void Update()
{
transform.Translate(Vector3.forward * 7 * Time.deltaTime);
maxDistance += 1 * Time.deltaTime;
if (maxDistance >= 5)
{
scriptBulletPool.MyInstance.returnBullet(bullet);
}
}
}
Shoot script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scriptShoot : MonoBehaviour
{
//public scriptBulletPool bulletPoolObj;
public GameObject bulletSpawnPoint;
void Update()
{
shoot();
}
private void shoot()
{
if (Input.GetMouseButtonDown(0))
{
// scriptBulletPool.MyInstance.getBullet(bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation);
scriptBulletPool.MyInstance.getBullet(bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation);
}
}
}
Bulletpool script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scriptBulletPool : MonoBehaviour
{
public GameObject bulletPrefab;
public List<GameObject> bulletPool;
public int poolSize;
private static scriptBulletPool myInstance;
public static scriptBulletPool MyInstance
{
get
{
return myInstance;
}
}
private void Awake()
{
if (myInstance == null)
{
myInstance = this;
} else if(myInstance != this)
{
Debug.LogError("Obj 1:", gameObject);
Debug.LogError("Obj 2:", myInstance.gameObject);
}
instantiatePool();
}
private void instantiatePool()
{
bulletPool = new List<GameObject>();
for (int i=0; i<poolSize; i++)
{
GameObject newBullet = Instantiate(bulletPrefab);
bulletPool.Add(newBullet);
newBullet.SetActive(false);
}
}
public GameObject getBullet(Vector3 targetPos, Quaternion targetRot)
{
GameObject newBullet = bulletPool[bulletPool.Count - 1];
newBullet.transform.position = targetPos;
newBullet.transform.rotation = targetRot;
newBullet.SetActive(true);
bulletPool.Remove(newBullet);
return newBullet;
}
public void returnBullet(GameObject bullet)
{
bulletPool.Add(bullet);
bullet.SetActive(false);
}
}