Counting times an animation is played?

Hi,

I’m working on a shooting program where every time the object shoots an animation is played. Because the shooting animation is activated from the Update() function, I can’t just put in shotsFired ++ as it would scale up a huge amount as it would be increased every frame. I tried shotsFired += 1 * Time.deltaTime however that didn’t work either. How do you suggest I keep count of the number of times an enemy has fired?

Could I start a timer that runs as long as the animation plays then stops and then increases the counter?

You should check out the teaching section:
http://forum.unity3d.com/viewforum.php?f=19

Has lots of tutorials for making shooting game. But for this little problem of yours, you should increase numbers when any triggering occurs, like shooting the gun.

I also recommend that you buy and read Will Goldstone’s book:

I’ve read the book twice, and I tried simply increasing the counter however because the trigger occurs as the result of a distance check that happens in Update() the number goes crazy high in only a couple seconds.

I would imagine the shooting animation is triggered with something like:-

if (Input.GetKeyDown("f")) {
    animation.Play("Shoot");
}

If so, you can just increment shotsFired inside the body of the “if” statement just after animation.Play.

As I said it is played from update().
I have:
“shotsFired ++;
Animation.play…”

Which is in a function that is called by another function that checks distance. The checkDistance() function is called every frame from Update(). Thus, shotsFired goes up every frame.
[/quote]

You can set a boolean flag the first time the animation is triggered and then use this to avoid incrementing shotsFired until the animation has finished:-

var shooting: boolean;


function Update() {
   ...

   if (!shooting  checkDistance()) {
      shooting = true;
      animation.Play("Shoot");
      shotsFired++;
   } else {
      shooting = animation.IsPlaying("Shoot");
   }

   ...
}

Hmmm, tried that and still I get the same result. :cry:

I also tried:
WaitForSeconds (2); //2 sec is the duration of the shooting animation
shotsFired ++;

In place of just shotsFired++; however I also got the same result that method.

EDIT:

With:

shooting = animation.IsPlaying(shoot);
	Debug.Log(shooting);
	
	if (!shooting) { 
      shooting = true; 
      animation.Play(shoot);
      WaitForSeconds (2);
      shotsFired++; 
   } 
   else { 
      shooting = animation.IsPlaying(shoot);
   }

shots fired never goes past 1.

Is the shooting animation set to loop? If so, try setting it to play once.