So I was using object pooling for some bullets on a gun script i made because i started off doing the normal destroying thing, but now I’m into the optimizing stage. However, i have a question about the object pooling with the ray casting that is going on, if i set the list of bullets to the position of the ray cast hit, shouldn’t each bullet go where the raycast hits a collider? It isn’t working out like that though, right now all the bullets being “spawned” are all staying in one place. Here is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour {
public List<GameObject> bullets;
public int pooledAmount = 30;
public float damage = 10f;
public float range = 100f;
public float impactForce = 40f;
public float fireRate = 15f;
public int maxAmmo = 10;
private int currentAmmo;
public float reloadTime = 1f;
private bool isReloading = false;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
public Animator animator;
private float nextTimeToFire = 0f;
void Start()
{
bullets = new List<GameObject>();
for (int i = 0; i < pooledAmount; i++)
{
GameObject obj = (GameObject)Instantiate(impactEffect);
obj.SetActive(false);
bullets.Add(obj);
}
currentAmmo = maxAmmo;
}
void OnEnable()
{
isReloading = false;
animator.SetBool("Reloading", false);
}
void Update () {
if (isReloading)
{
return;
}
if(currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
IEnumerator Reload()
{
isReloading = true;
Debug.Log("Reloading..");
animator.SetBool("Reloading", true);
yield return new WaitForSeconds(reloadTime - .25f);
animator.SetBool("Reloading", false);
yield return new WaitForSeconds(.25f);
currentAmmo = maxAmmo;
isReloading = false;
}
void Shoot()
{
currentAmmo--;
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
muzzleFlash.Play();
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
if(hit.rigidbody != null)
{
hit.rigidbody.AddForce(hit.normal * impactForce);
}
for (int i = 0; i < bullets.Count; i++)
{
if (!bullets[i].activeInHierarchy)
{
bullets[i].transform.position = hit.transform.position;
bullets[i].SetActive(true);
break;
}
}
}