[C#] [2D] Animation mostly not working

Hello

I’ve been working on a small 2D platformer game for my little brother. The main character (a monkey) is supposed to be able to use a sword to damage enemies. I’ve come across a problem trying to animate this sword. The animation is supposed to be pretty simple:

  1. First frame: sword is disabled
  2. Second frame: sword becomes enabled
  3. Middle frame: sword’s X value has changed so it looks like it’s thrusting forward
  4. Second to last frame: sword enabled
  5. Last frame: sword disabled

Below, I will include a few pictures of the animation, animator and the code I used to call the animation.

The problem is that sometimes the animation does display correctly, but most of the time it doesn’t do anything.

I’m still fairly new to using animations in Unity, and I was wondering if anyone could help me solve this little problem. Many thanks in advance.


Animator

alt text

Transition any state - sword attack

alt text

Transition sword attack - idle

alt text

Animation

alt text

Code used

if (anim.GetBool("Sword")) 
{
	anim.SetBool("Sword", false);
}

if (Input.GetKeyUp (KeyCode.Mouse0)) 
{
	anim.SetBool("Sword", true);
}

[EDIT]

Extra information:

  • I put a Debug.Log in the statement where it sets the Sword bool to true, which does show up when I press the button, but I don’t see the “Sword” checkbox in the animator being ticked on when I do so
  • The code for this animation is in the same script as the one in which I control the player’s jumping and walking animations, although these two use different values (a bool called “On Ground” and a float called “Speed”) to control the animations

if (anim.GetBool(“Sword”))
{
anim.SetBool(“Sword”, false);
}

if (Input.GetKeyUp (KeyCode.Mouse0))
{
anim.SetBool(“Sword”, true);
}

As you are using in update method, when you start the animation " anim.SetBool(“Sword”, true);" same time in update its getting false which will not work like that.
Add a public method to make it false.

public void swordFalse()
{
anim.SetBool(“Sword”, false);
}

call this function on the end of the frame to let your attack animation to complete.

secondly uncheck the fixed duration and “has exit time” options. hope it will work.