Trying to make an fps and i need to combine an Iteration with a void:
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour {
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public int maxAmmo = 30;
public int currentAmmo;
public int bulletsLeft = 200;
public float reloadTime = 1f;
public AudioClip reload1;
private bool isReloading = false;
AudioSource audio;
private bool playReloadSound = false;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
public Animator animator;
void Start ()
{
currentAmmo = maxAmmo;
audio = GetComponent<AudioSource>();
animator.SetBool("Fire", false);
}
void Update () {
if (isReloading)
return;
if (playReloadSound)
audio.PlayOneShot(reload1);
playReloadSound = false;
if (currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
StartCoroutine(Shoot());
AudioSource shoot = GetComponent<AudioSource>();
shoot.Play();
}
if (bulletsLeft <= 0) return;
}
IEnumerator Reload () //combine this
{
isReloading = true;
Debug.Log("Reloading...");
animator.SetBool("Reloading", true);
playReloadSound = true;
yield return new WaitForSeconds(reloadTime);
animator.SetBool("Reloading", false);
currentAmmo = maxAmmo;
isReloading = false;
}
private void Reload2() //with this
{
if (bulletsLeft <= 0) return;
int bulletsToLoad = maxAmmo - currentAmmo;
int bulletsToDeduct = (bulletsLeft >= bulletsToLoad) ? bulletsToLoad : bulletsLeft;
bulletsLeft -= bulletsToDeduct;
currentAmmo += bulletsToDeduct;
}
IEnumerator Shoot()
{
muzzleFlash.Play();
animator.SetBool("Fire", true);
currentAmmo--;
yield return new WaitForSeconds(0.05f);
animator.SetBool("Fire", false);
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target> ();
if (target != null)
{
target.TakeDamage (damage);
}
GameObject impactGo = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGo, 2f);
}
}
}