Can´t find the infinite loop in this script
Hi, I´m making a game where my character should be able to hit, and only change to idle state (or any other anim state) if the "hit animation" ends. To achieve that I used an event function and a boolean . The thing is that, if I tap rapdly the "S" key (really fast, probably matching the exact frame where the animation event function gets called), the player freezes at the last frame of the hit animation, not the game, but the player. I guess it is an infinite loop since the console doesn´t notify anything. Any ideas??
using UnityEngine;
using System.Collections;
public class leono : MonoBehaviour {
public float moveSpeed;
private Animator animator;
private bool fighting;
void Awake () {
animator = GetComponent<Animator>();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Player hit
if (Input.GetKeyDown (KeyCode.S)&& !fighting) {
Debug.Log (" fighting true ");
fighting = true;
animator.SetInteger ("leono", 2);
}
//Player move right
else if (Input.GetKey (KeyCode.RightArrow) && !fighting ) {
transform.localScale = new Vector3 (1f, 1f, 1f);
animator.SetInteger ("leono", 1);
GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveSpeed, GetComponent<Rigidbody2D> ().velocity.y);
}
//Return to idle from moving right
if (Input.GetKeyUp (KeyCode.RightArrow)&& !fighting ) {
animator.SetInteger ("leono", 0);
}
//Player move left
else if (Input.GetKey (KeyCode.LeftArrow)&& !fighting ) {
transform.localScale = new Vector3 (-1f, 1f, 1f);
animator.SetInteger ("leono", 1);
GetComponent<Rigidbody2D> ().velocity = new Vector2 (-moveSpeed, GetComponent<Rigidbody2D> ().velocity.y);
}
//Return to idle from moving left
if (Input.GetKeyUp (KeyCode.LeftArrow)&& !fighting ) {
animator.SetInteger ("leono", 0);
}
}
//This function gets called at the end of the animation with an animation event
void defaultState (){
fighting = false;
Debug.Log (" fighting false ");
animator.SetInteger ("leono", 0);
}
}
You are setting fighting
to true, but you are setting it to false only in defaultState
function. Where do you call it?
Hello, the defaultState function is called in an animation event, which is placed after the last frame of the hitting animation.
That's it, when you press keys very fast, it sets fighting to true again but you never call defaultState function ever again. You may want to check if animation is finished to S key check.
Your answer
Follow this Question
Related Questions
How to get perfect position animation with root motion? 1 Answer
Add Event in animation from another Gameobject 5 Answers
How to add Animation Events in the Timeline editor? 5 Answers
PROBLEM WITH ANIM.SETBOOL NOT WORKING 0 Answers
Unity Animation 0 Answers