hey all, sorry about this but im still very new to C# and i find coroutines quite confusing. basically i made section of script to control the fire rate of a gun and i get a ton of errors when trying to use it. i posted this in the answers section but haven’t gotten any replies so i thought id ask here.
i originally had the code:
using UnityEngine;
using System.Collections;
public class Wep_gun01 : MonoBehaviour {
public GameObject BulletPrefab;
public GameObject BulletSpawn;
float bulletimpulse = 10f;
float ammo = 35f;
private bool canfire = true;
public float firerate = 0.2f;
// Use this for initialization
void Start () {
StartCoroutine(firerate());
}
// Update is called once per frame
void Update () {
if(canfire == false) {
IEnumerator firerate() {
yield return WaitForSeconds(firerate);
canfire = true;
}
}
if(Input.GetButton("Fire1") ammo >= 0) {
if(canfire == true) {
GameObject thelaser = (GameObject) Instantiate(BulletPrefab, BulletSpawn.transform.position + BulletSpawn.transform.forward, BulletSpawn.transform.rotation);
thelaser.rigidbody.AddForce( -BulletSpawn.transform.forward * bulletimpulse, ForceMode.Impulse);
ammo = ammo - 1f;
canfire = false;
}
}
if(Input.GetButtonDown("Reload") ammo < 35) {
ammo =35f;
}
}
but that came up with a ton of errors, now im using this:
using UnityEngine;
using System.Collections;
public class Wep_gun01 : MonoBehaviour {
public GameObject BulletPrefab;
public GameObject BulletSpawn;
float bulletimpulse = 10f;
float ammo = 35f;
private bool canfire = true;
public float firerateset = 0.2f;
// Use this for initialization
void Start () {
StartCoroutine(firerate());
}
IEnumerator firerate() {
yield return new WaitForSeconds(firerateset);
canfire = true;
}
// Update is called once per frame
void Update () {
if(Input.GetButton("Fire1") ammo >= 0) {
if(canfire == true) {
GameObject thelaser = (GameObject) Instantiate(BulletPrefab, BulletSpawn.transform.position + BulletSpawn.transform.forward, BulletSpawn.transform.rotation);
thelaser.rigidbody.AddForce( -BulletSpawn.transform.forward * bulletimpulse, ForceMode.Impulse);
ammo = ammo - 1f;
canfire = false;
}
}
if(Input.GetButtonDown("Reload") ammo < 35) {
ammo =35f;
}
}
}
but i dont know how to ‘call’ the ienumerator to activate when canfire = false.
any help would be much appreciated.