- Home /
Animation event not always triggered
System: Unity 4.5.2
2d Game in c#
I have a character who throws his weapon in an animation. It is realized by two animation events. The first event detaches the weapon (throw) and the second creates the new instant of the weapon. While the animation is running a bool variable is set to false (readyToThrow - in the same methode as the throw animation is started) and is set back to true once the new weapon is created (second event). In rare cases the second event is not triggerd and the character has no weapon.
I tried to reproduce it in a small project. I used the 2D Platformer (https://www.assetstore.unity3d.com/en/#!/content/11228). I increased the 'Sample' from 3 to 60 in the animation clip Shoot and added two events.
I also added code:
public class PlayerControl : MonoBehaviour
{
public bool isReady = true;
public void EventShot1() {
Debug.Log("EventShot1");
}
public void EventShot2() {
Debug.Log("EventShot2");
isReady = true;
}
}
public class Gun : MonoBehaviour
{
void Update ()
{
// If the fire button is pressed...
if(Input.GetButtonDown("Fire1") && playerCtrl.isReady)
{
Debug.Log("Shot0");
playerCtrl.isReady = false;
// ... set the animator Shoot trigger parameter and play the audioclip.
}
}
How to reproduce:
You have to move continually left and right (alternately) and shoot as fast as possible. After a short time you can't shoot because is ready is false.
Log:
Massage: Amount:
Shot0 59
EventShot1 58
EventShot2 58
Probably fix:
Change animator from 'Animate Physics' to 'Normal'. I couldn't check my game atm.
Any help would be greatly appreciated.
I dont like relying too much on animation driven events just because they can sometimes hiccup like this. I've found its much easier to just make your own "control" over the events by using a coroutine.
void Update ()
{
if(Input.GetButtonDown("Fire1") && playerCtrl.isReady)
{
playerCtrl.ThrowWeapon();
}
}
//In the player control script...
public bool isReady = true;
public float throwTimer = 1.5f; // put whenever you want the throw to refresh, match the ti$$anonymous$$g up to your animation.
public void ThrowWeapon(){ // this would be your EventShot1
isReady = false;
StartCoroutine(ThrowTimer());
}
IEnumerator ThrowTimer(){
yield return new WaitForSeconds(throwTimer);
isReady = true; // put EventShot2 here
}
Your answer
Follow this Question
Related Questions
Animation events firing all at once in mirrored blend tree 1 Answer
4.3, Animation Event in Animations from Mixamo 1 Answer
Mecanim animation layers and animation events 3 Answers
Mecanim animation events 2 Answers
Weapon System and Animation Events 0 Answers