- Home /
ammo counter, counts wrong
Hi guys! i have an error with my ammo count, it shows up on the screen and everything but it substracts two instead of one each time. If i remove the "static" var it counts one and one. but with a static var (its needed) it counts double, help?
-thanks in advance
#pragma strict
var muzzleFlash : Renderer;
var muzzleLight : Light;
var reload = true;
static var Ammo = 31;
function Start () {
muzzleFlash.enabled = false;
muzzleLight.enabled = false;
}
function Update () {
if(Ammo >= 0){
if(Input.GetButtonDown("Fire1")) {
Shoot();
}
}
}
function Shoot ()
{
muzzleFlash.renderer.enabled = true;
muzzleLight.enabled = true;
yield WaitForSeconds(0.02);
Ammo -= 1;
muzzleFlash.renderer.enabled = false;
muzzleLight.enabled = false;
audio.Play();
}
function OnGUI (){
GUI.Label (Rect (Screen.width/4+Screen.width/4+Screen.width/4+Screen.width/8,Screen.height/4+Screen.height/4+Screen.height/4+Screen.height/8,50,30), Ammo.ToString());
}
I wonder if it's just how it's getting called.
$$anonymous$$aybe include an isFiring boolean in your code, that will only call Shoot() when false, when you go through the Shoot function set it to true before the yield and false afterwards.
What might be happening is it doesn't actually wait 0.02 before firing again.
I'm going to have to go with what Jeremy2300 said, you may want to add a bool in there to make sure it's only firing when it's suppose to.
But I did find something else that may cause a problem. this: if(Ammo >= 0){ should probably just be "less than" ins$$anonymous$$d of "less than or equal to". With the way it is right now you will be able to fire when your ammo reaches 0. (Unless you are accounting for one in the chamber and this is only for the magazine)
Answer by swalex · Mar 16, 2014 at 01:58 AM
Do you probably have two instances of your ammo counter behaviour in your scene (for a second player probably)? They would both call Shoot() on 'Fire1' and they would both decrease Ammo by 1. If it is a non-static field, each behaviour instance would decrease its own ammo counter, but in your case they would both decrease the same counter.
Good point, I didn't think about that one...but that's probably the issue with his counter.
Your answer
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Limit on GUI Components? 0 Answers
Rapid fire Help 1 Answer
Android touch gui help!!! 2 Answers