Using waitforseconds to put delay between gunshots
HELP! I'm using unity 4.6.9, and I have a script to make a gun shoot. It works perfectly, except you can fire as fast as you want, as in several bullets per second. I want to have like a one second delay between the shots that you can fire. However, after trying again and again to get a yield waitforseconds (5); to work, I haven't been able too. The script below does nothing. Or rather, it does exactly as it does normally, with absolutely no delay. I've even tried ramping the delay up to 100, and it still doesn't do anything. I've been trying for days!!!
var projectile : Rigidbody;
var speed = 10;
function wait() {
yield WaitForSeconds(1);
}
function Update () {
if(Input.GetMouseButtonDown(0)) {
clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector3 (0, 0, speed));
audio.Play();
Destroy (clone.gameObject, 5);
}
wait();
}
Please help!!!
Answer by TBruce · Sep 28, 2016 at 04:55 PM
This will work for you
var projectile : Rigidbody;
var speed = 10;
// the time allowed between shots (in seconds or parts thereof)
// the smaller the value the faster shots can occur
var timeBetweenShots = 1;
// flag to determine if a shot was fired
private var shotFired = false;
function FireShot()
{
// fire the shot
clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector3 (0, 0, speed));
audio.Play();
Destroy (clone.gameObject, 5);
// do not allow another shot until timeBetweenShots has elapsed
yield WaitForSeconds(timeBetweenShots);
// reset the shot flag so shooting can resume
shotFired = false;
}
function Update ()
{
if ((!shotFired) && (Input.GetMouseButtonDown(0)))
{
// immediately set the shot flag so another shot can not be made
shotFired = true;
FireShot();
}
}
I am happy that this is working for you. Would you be so kind as to click the "Accept" button above to accept the answer? Thank you!
Happily! That script was bothering me for ages!
Your answer
Follow this Question
Related Questions
StartCoroutine not listening to parameters 1 Answer
How do I assign values to variables in the Update function only ONCE? 1 Answer
BasicFPS controller "Can not be loaded" 0 Answers
When player enters area. Object that script is attached to walks toward the entering object(player). 1 Answer
UNITY shooting script does nothing 1 Answer