I have a gun that fires a laser but i want to make it so that the laser only remains active for a few seconds and then has to cooldown before it can be used again i have the following code for the laser and the cooldown seems to be working but the problem is that the player can keep the mouse button held down and just perpetually keep on fireing.
public class LaserScript : MonoBehaviour {
LineRenderer line;
Light light;
ParticleSystem particle;
float cooldown;
public GameObject explosion;
void Start () {
line = gameObject.GetComponent<LineRenderer> ();
light = gameObject.GetComponent<Light>();
light.enabled = false;
line.enabled = false;
cooldown = Time.time;
}
void Update () {
if (Input.GetButtonDown ("Fire1")) {
StopCoroutine("fireLaser");
StartCoroutine("fireLaser");
}
}
IEnumerator fireLaser(){
light.enabled = true;
line.enabled = true;
while (Input.GetButton("Fire1") && Time.time >= cooldown) {
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
line.SetPosition(0, ray.origin);
if(Physics.Raycast(ray, out hit, 100)){
line.SetPosition(1, hit.point);
if(hit.rigidbody){
hit.rigidbody.AddForceAtPosition(transform.forward * 5, hit.point);
Instantiate (explosion, hit.transform.position, transform.rotation);
hit.transform.gameObject.SetActive(false);
}
}
else{
line.SetPosition(1, ray.GetPoint(100));
}
yield return null;
}
line.enabled = false;
light.enabled = false;
cooldown = Time.time + 1;
}
}
any help you guys can provide id be really gratefull for.
thanks in advance.
Kiwasi
2
In essence there is nothing in your while loop that will trigger the laser to stop firing.
You need a second timer. Try the following at line 27-28. You will also need to throw in a declaration for float FireTimer. Adjust the actual time to suit your needs:
FireTimer = Time.time + 0.5f;
while (Input.GetButton("Fire1") && Time.time >= cooldown && Time.time <= FireTimer)
On a separate note StopCoroutine is not buying you anything, the coroutine will stop itself if the key is released.