- Home /
Fps game gun reloading problem
I'm making a FPS game, but reloading won't work!I'm writing it with JavaScript Can anyone help?Code:
public var BulletPrefab : Transform;
public var BulletSpeed : float = 6000;
public var GunMuzzle : Transform;
public var ClipSize : float = 30;
public var Clip : float = 30;
public var ReloadTime : float = 2.0;
function Update () {
if (Input.GetButtonDown("Fire1")) {
if (!BulletPrefab | !BulletSpeed ) {
Debug.Log("[shoot] Undefined Variables");
} else {
if (Clip >0) {
var BulletSpawn = Instantiate (BulletPrefab,GunMuzzle.transform.position,Quaternion.identity);
BulletSpawn.rigidbody.AddForce(transform.forward * BulletSpeed );
Clip -= 1;
}
}
}
}
if (Clip < 1 ){
Debug.Log("Reloading");
yield WaitForSeconds (ReloadTime) ;
Clip = ClipSize ;
}
Rule #1 of Unity Answers: format your code so we can read it.
Yes! Format your code by highlighting the code an press the "10101" button. I already did this for you.
please edit your question to properly format the code. We will be happy to answer your question but please dont make us struggle to figure out whats going on.
Answer by Anxo · Jun 07, 2011 at 07:16 PM
you cant have a yield in an update function. What you can do is use a while loop in your start function.
function Start(){
while(true)
{
while(!Reloading) yield;
Debug.Log("reloading");
yield WaitForSeconds(ReloadTime);
Clip = ClipSize;
Reloading = false;
}
}
function Update(){
if(Input.GetButtonDown("Fire1"))
{
Reloading = true;
}
}
please remember that you will get a much faster answer if you ask your question in a way that does not give people a hard time ot figure out what the problem is.
I'm trying to wrap my head around this; does your first yield statement kick out to the Update(), run through one frame, then resume?
my first while statement just makes sure that the start function loops. As you know Chris, Start only runs once just before the update function. so the while(true) which is always true will cause the while to loop all game long. Without a yield or some sort of delay, a while true in start will crash your game/editor but with a delay it works well. the second while tells it not to go on unless reloading is true, when reloading becomes true it will pass that line of code and start to reload. at the end reloading is set back to false so it will only run reload once till reloading is set back to true externally.
OH $$anonymous$$Y GOD!Thank you, Thank you! It Works now :D Thanks again
@Anxo Ah, excellent! I know about Start() only running once, but I haven't dealt with yield before. Thanks for the explanation.
Your answer
![](https://koobas.hobune.stream/wayback/20220612100850im_/https://answers.unity.com/themes/thub/images/avi.jpg)