Hello, I have Player Controller Script that allows me to have the Player to have idle, walk and jump with animation. When I tried to add run, the Player runs but the animation is not working. I was following ThinkCitric's guides and I could not figure out what went wrong.
VIDEO
VIDEO
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Spine.Unity;
public class PlayerController : MonoBehaviour
{
public SkeletonAnimation skeletonAnimation;
public AnimationReferenceAsset idle, walking, jumping, running;
public string currentState;
public float speed;
public float movement;
private Rigidbody2D rigidbody;
public string currentAnimation;
public float jumpSpeed;
private Vector2 characterScale;
public string previousState;
public float runSpeed;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
currentState = "Idle";
SetCharacterState(currentState);
characterScale = transform.localScale;
}
// Update is called once per frame
void Update()
{
Move();
}
//sets character animation
public void SetAnimation(AnimationReferenceAsset animation, bool loop, float timeScale)
{
if (animation.name.Equals(currentAnimation))
{
return;
}
Spine.TrackEntry animationEntry = skeletonAnimation.state.SetAnimation(0, animation, loop);
animationEntry.TimeScale = timeScale;
animationEntry.Complete += AnimationEntry_Complete;
currentAnimation = animation.name;
}
//Do something after animation completes
private void AnimationEntry_Complete(Spine.TrackEntry trackEntry)
{
if (currentState.Equals("Jumping"))
{
SetCharacterState(previousState);
}
}
//Checks character state and sets the animation accordingly
public void SetCharacterState(string state)
{
if (state.Equals("Walking"))
{
SetAnimation(walking, true, 1.5f);
}
else if (state.Equals("Jumping"))
{
SetAnimation(jumping, false, 1f);
}
else if (state.Equals("Running"))
{
SetAnimation(running, true, 1f);
}
else
{
SetAnimation(idle, true, 1f);
}
currentState = state;
}
public void Move()
{
movement = Input.GetAxis("Horizontal");
rigidbody.velocity = new Vector2(movement * speed, rigidbody.velocity.y);
if (movement != 0)
{
if (!currentState.Equals("Jumping"))
{
SetCharacterState("Walking");
}
if (movement > 0)
{
transform.localScale = new Vector2(characterScale.x, characterScale.y);
}
else
{
transform.localScale = new Vector2(-characterScale.x, characterScale.y);
}
}
else
{
if (!currentState.Equals("Jumping"))
{
SetCharacterState("Idle");
}
}
if (Input.GetButtonDown("Jump"))
{
Jump();
}
if (Input.GetKey(KeyCode.LeftShift))
{
Run();
}
}
public void Jump()
{
rigidbody.velocity = new Vector2(rigidbody.velocity.x, jumpSpeed);
if (!currentState.Equals("Jumping"))
{
previousState = currentState;
}
SetCharacterState("Jumping");
}
public void Run()
{
rigidbody.velocity = new Vector2(movement * runSpeed, rigidbody.velocity.y);
if (!currentState.Equals("Running"))
{
previousState = currentState;
}
SetCharacterState("Running");
}
}