Player animation FSM stopped working
First time Unity and c# user here. So when I was trying to make the FSM for player animation, it was going well and everything was working until I tried to add a double jump state. Now the whole FSM won't register, even when I comment out the new part. Unity isn't showing any errors, and I'm at a loss as to what's going on. Here's my code. The FSM is at the end
using UnityEngine;
public class PlayerControl : MonoBehaviour { private Rigidbody2D rb; private Animator anim;
private enum State
{
idle,
running,
jumping,
falling,
djumping
};
private State state = State.idle;
private Collider2D coll;
[SerializeField] private LayerMask ground;
[SerializeField] private float speed = 5f;
[SerializeField] private float jforce = 10f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>(); //links the correct components to their respective variables
anim = GetComponent<Animator>();
coll = GetComponent<Collider2D>();
}
// Update is called once per frame
void Update()
{
Movement();
Animationstate();
anim.SetInteger("state", (int)state);
}
private void Movement() //Movement control
{
float hdirection = Input.GetAxis("Horizontal");
if (hdirection < 0) // When the negative horzintal movement is activated
{
rb.velocity = new Vector2(-speed, rb.velocity.y); //apply an x vector of -5 (moves to the left)
transform.localScale = new Vector2(-1, 1); //sets x scale to -1 (faces sprite to the left)
}
else if (hdirection > 0) // When the positive horzintal movement is activated
{
rb.velocity = new Vector2(speed, rb.velocity.y); //apply an x vector of -5 (moves to the left)
transform.localScale = new Vector2(1, 1); //sets x scale to 1 (faces sprite to the right)
}
if (Input.GetButtonDown("Jump") && coll.IsTouchingLayers(ground)) // when the Space key is pressed (Keydown gives single input instead of held)
{
rb.velocity = new Vector2(rb.velocity.x, jforce); //apply a y vector equal to the jump force (moves upward)
state = State.jumping; // set the payer state to jumping
}
else if (Input.GetButtonDown("jump") && (state == State.jumping || state == State.falling)) //double jump can only be applied if in jumping or falling state
{
rb.velocity = new Vector2(rb.velocity.x, jforce);
state = State.djumping;
}
}
private void Animationstate() //FSM for setting the player animation
{
if (state == State.jumping || state == State.djumping) // if player is in the jumping or double jumping state and starts to go down, put player in falling state
{
if (rb.velocity.y < .1f)
{
state = State.falling;
}
}
else if (state == State.falling) //if player is in falling state and touches ground, put in idle state
{
if (coll.IsTouchingLayers(ground))
{
state = State.idle;
}
}
else if (Mathf.Abs(rb.velocity.x) > 1)
{
state = State.running;
}
else
{
state = State.idle;
}
}
}
Comment