So i have made myself a script for a musket that after 1 shot it Stops for a few seconds (Reloading) and then can be fired again. But it wont work and i don’t know why.
var Bullet : Rigidbody;
var Spawn : Transform;
var BulletSpeed : float = 5000;
var ReloadTime : float = 2;
private var FireShot = true;
function Start () {
}
function Update () {
if(FireShot == true){
if(Input.GetButtonDown(“Fire1”)){
var bullet1 : Rigidbody = Instantiate(Bullet,Spawn.position,Spawn.rotation);
bullet1.AddForce(transform.forward *BulletSpeed);
audio.Play();
FireShot = false;
}
}
if(Input.GetButtonUp(“Fire1”)){
yield WaitForSeconds(ReloadTime);
FireShot = true;
}
}
Cannot use yield WaitForSeconds in Update. You need to use a coroutine. Read This:
Unity Coroutines
and replace your script with this:
var Bullet : Rigidbody;
var Spawn : Transform;
var BulletSpeed : float = 5000;
var ReloadTime : float = 2;
private var FireShot = true;
function Update () {
if(FireShot == true){
if(Input.GetButtonDown("Fire1")){
var bullet1 : Rigidbody = Instantiate(Bullet,Spawn.position,Spawn.rotation);
bullet1.AddForce(transform.forward *BulletSpeed);
audio.Play();
FireShot = false;
}
}
if(Input.GetButtonUp("Fire1")){
Reload();
}
}
function Reload(){
yield WaitForSeconds(ReloadTime);
FireShot = true;
}
Thanks! But theres one problem, if i shoot really fast with your script, it shoots several bullets other then just one, any solution? other then that its great!
Try this.
var Bullet : Rigidbody;
var Spawn : Transform;
var BulletSpeed : float = 5000;
var ReloadTime : float = 2;
private var FireShot = true;
function Update () {
if(FireShot == true){
if(Input.GetButtonDown("Fire1")){
var bullet1 : Rigidbody = Instantiate(Bullet,Spawn.position,Spawn.rotation);
bullet1.AddForce(transform.forward *BulletSpeed);
audio.Play();
FireShot = false;
Reload();
}
}
}
function Reload(){
yield WaitForSeconds(ReloadTime);
FireShot = true;
}
Works Perfectly! thanks a bunch!