- Home /
Code isn't Recursive in update?
Hey there. I have a problem with a section of code in my weapon script. Simply put, it won't call fire multiple times :
void Update() {
//Updates ammo Meter
if(ammoBox == 0 && clipBullets == 0)
{
lcdMeter.text = "--";
}
else
lcdMeter.text = clipBullets.ToString();
int count = Input.touchCount;
for(int i = 0;i < count; i++)
{
Touch touch = Input.GetTouch(i);
bool shouldLatchFinger = false;
Vector2 firstTouch = Vector2.zero;
if(touch.phase == TouchPhase.Began)
{
firstTouch = new Vector2(touch.position.x, -touch.position.y + Screen.height);
print("i");
}
else if(touch.phase == TouchPhase.Canceled || touch.phase == TouchPhase.Ended)
{
firstTouch = Vector2.zero;
print(firstTouch);
}
if(fireButtonRect.Contains(firstTouch))
{
print("Fire!");
// Keep firing until we used up the fire time
if( prevFire + fireRate <= Time.time)
{
FireWeapon();
prevFire = Time.time;
}
}
}
}
The problem is that it doesn't trigger the "Fire!" continuously. it fire it once...which I really don't get...
Answer by Bunny83 · Oct 18, 2011 at 11:27 PM
Your problem seems to be the declaration of your firstTouch variable. You declared it inside Update (even inside the touch loop) so it gets reset every time you run through the loop. You set the firstTouch var only at TouchPhase.Began which happens only once when you start touching the display.
Just move the declaration out of Update and put it into your script-scope, that should do the trick.
Answer by DaveA · Oct 15, 2011 at 06:37 PM
Are you sure about if( prevFire + fireRate = ?
Yes. it has worked before - when I was was using a recursive Button. And note that the print function is outside that if statement.
@DaveA: well i was also confused because the if statement is reversed as you would expect. Usually you put the value that you want to check first. In this case the variable that is going to change is Time.time, so you would check if Time.time is greater than your reference. I'm not sure how those peoples $$anonymous$$ds works. It's so un-natural the other way round but it doesn't matter of course. It's just hard to read.
Personally i would calculate the "timeout" value at the point of assignment:
if( Time.time >= timeOut )
{
FireWeapon();
timeOut = Time.time + fireRate;
}