- Home /
Glitchy variable when updating through a function
I have a simple shooting game with two gameobjects - the gun and the ammo controller. This is my script for the ammo controller:
#pragma strict
var ammo:int;
var gun:GameObject;
function Start () {
ammo=100;
}
function Update() {
Debug.Log(ammo);
}
function Shoot () {
ammo-=1;
gun.GetComponent(gun_script).ShootEffect();
}
The function Shoot () is called by the gun when I press the left mouse button. The problem is that the ammo variable doesn't decrease with 1 after every time the function is called. I shoot like 10 times, wait some seconds and the variable starts to decrease very fast until it gets to 90 (some seconds after I finished shooting). However, if I put the ammo decreasing code in the Start or the Update function this bug doesn't appear. For example:
function Start() {
ammo=100;
while(true) {
ammo-=1;
yield WaitForSeconds(0.5);
}
}
This time it works but I don't want to decrease the ammo every half a second. Only when the function is called. Can somebody help me?
Sorry for my bad English.
Answer by pheash · Aug 06, 2013 at 11:49 AM
Heya, Not quite sure if I am right, but to me it sounds like the problem might be in the way you call the shoot function. Using Input.GetMouseButtonDown is only called once whereas Input.GetMouseButton would call the function while the button is down, leading to it being called multiple times.. here is a link to the documentation http://docs.unity3d.com/Documentation/ScriptReference/Input.GetMouseButtonDown.html If that doesnt help could you paste the bit where you call the Shoot function.
Answer by ivan_hellgames · Aug 06, 2013 at 12:54 PM
I use GetMouseButton. Here is the code:
if(Input.GetMouseButton(0)) {
if(!mesh.animation.isPlaying && ammo_controller.GetComponent(ammo_script).ammo>0){
mesh.animation.Play();
MuzzleFlash();
ammo_controller.GetComponent(ammo_script).Shoot();
}
}
It checks if the gun is not shooting (the animation is not playing) and if I have ammo. I tried with GetMouseButtonDown but the problem is the same.