I got into a Unity-Tutorial and halfway-through I face this weird problem. I used this code so that my player may attack if he pressed a leftShift. When the player attacks, the animation starts playing in a loop - he never stops attacking and debugging show that attack is never false after the first "leftShift"-Input.
I removed the loops from the animator etc. - but that doesn't seem to be the problem because "attack" never get's to false anyways. I tried different approaches. If I set "attack = false" immediately after attacking, he doesn't attack at all.
Sorry for asking such a beginner question but I can't seem to find my error.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
[SerializeField]
private float movementSpeed;
private bool facingRight = true;
private Animator myAnimator;
private bool attack = false;
// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
void Update()
{
HandleInput();
Debug.Log(attack);
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
HandleMovement(horizontal);
Flip(horizontal);
HandleAttacks();
ResetValues();
}
private void HandleMovement(float horizontal)
{
if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
{
myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
}
}
private void HandleAttacks()
{
if (attack)
{
myAnimator.SetTrigger("attack");
}
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
attack = true;
}
attack = false;
}
private void Flip(float horizontal)
{
if(horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private void ResetValues()
{
attack = false;
}
}