- Home /
How can I change a mecanim animation by pressing a key?
Hi!
I have a character with 2 animations. One is just an idle that will loop forever until I press the spacebar (I changed the tag to 'Activate'). From there it will transition into a series of other animations.
I have set this up in the Animator window and I made a boolean parameter called 'hitSpace' to be used in a script.
This is the control script I wrote. I hooked it up to the character but it does nothing! It doesn't give any errors but it also doesn't show anything in the console when I press space (maybe it doesn't usually do that anyway?).
Can anyone help me?
using UnityEngine;
using System.Collections;
public class Alien_Behaviour : MonoBehaviour {
// Use this for initialization
private Animator anim;
private bool hitSpace;
void Start ()
{
anim = GetComponent<Animator>();
hitSpace = false;
}
// Update is called once per frame
void Update ()
{
if(Input.GetButtonDown("Activate"))
{
hitSpace = true;
anim.SetBool("hitSpace", hitSpace);
}
else
{
hitSpace = false;
anim.SetBool("hitSpace", hitSpace);
}
}
}
Well, first thing first, you are using a lot of code there for something that should be very simple:
void Update
{
anim.SetBool("hitSpace", Input.GetButtonDown("Activate"));
}
That should enough to handle the true/false value of the "hitSpace" parameter on the animator. The problem is more likely to be on the transitions of the animator controller.
Okay, thank you for the better code it's much cleaner. I'm no good at scripting :)
I found out the code was working after all, but I was testing it from the scene viewport ins$$anonymous$$d of the ingame view, and I guess it doesn't read the keyboard input then! How silly of me!
Answer by Iskander · Jul 29, 2014 at 04:18 PM
I'll copy the solution to my problem in this answer box if it can be of help to someone:
I found out the code was working after all, but I was testing it from the scene viewport instead of the ingame view, and I guess it doesn't read the keyboard input then! How silly of me!