Shooting with Raycasts object pooling

Updated on July 4, 2017 in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on July 4, 2017

For those of you that follow the Shooting with Raycasts tutorial on youtube by brackeys, Here is a object pooling version of mine that I made, it works the same as the original but is A lot more optimum if you decide to cut down on the garbage collection

 

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;
 }
 }
 }
  • Liked by
  • maxartz15
  • Leon Laci
Reply