- Home /
problem not playing animation on keyDown
ROOKIE QUESTION. I am trying to make an animation to work when you press a key down but I can only get it work with en key pressed. This is simply what I have
if(Input.GetKeyDown("6")){
animation["myanimation"].speed = speed/10;
animation.Play("myanimation");
}
I already know a way to make it work that is like this:
var myanimation = false;
function Update(){
if(Input.GetKeyDown("6")){
myanimation = true;
}
if(myanimation == true){
animation["myanimation"].speed = speed/10;
animation.Play("myanimation");
if(/*myanimation finish*/){
myanimation = false;
}
}
}
the thing is that I want to know if there is a simple way to do this, so my question is how can I make a complete animation pressing down a key?
Answer by DaveA · Apr 30, 2011 at 06:22 AM
It looks like that first part should just work. If you need to know if the animation is still playing, check animation.IsPlaying http://unity3d.com/support/documentation/ScriptReference/Animation.IsPlaying.html
Answer by john 9 · May 12, 2011 at 02:02 AM
This is what i wrote for the same problem
function Awake() { animation["Idle"].layer = 0; animation["Run"].layer = 1; animation["Jump"].layer = 2; animation["Dead"].layer = 3; }
function Update() { if (Input.GetKey("d")) { animation["Run"].wrapMode = WrapMode.Loop; animation.Play("Run");
} else{ if (Input.GetKeyUp("d")) animation.Stop(); animation["Idle"].wrapMode = WrapMode.Loop; }
if (Input.GetKey("a")){ animation["Run"].wrapMode = WrapMode.Loop; animation.Play ("Run"); } else{ if (Input.GetKeyUp("a")) animation.Stop(); animation.CrossFade ("Idle");
}
if (Input.GetKey("right")) { animation["Run"].wrapMode = WrapMode.Loop; animation.Play("Run");
} else{ if (Input.GetKeyUp("right")) animation.Stop(); animation["Idle"].wrapMode = WrapMode.Loop; }
if (Input.GetKey("left")){ animation["Run"].wrapMode = WrapMode.Loop; animation.Play ("Run"); } else{ if (Input.GetKeyUp("left")) animation.Stop(); animation.CrossFade ("Idle");
}
if (Input.GetButtonDown("Jump")) { animation.CrossFade("Jump"); } else{ animation.CrossFade("Idle"); }
} Don't know if this will help?
You just need one else to check if nothing ELSE is happening play idle ins$$anonymous$$d of trying to play idle when the key is released
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) { animation.CrossFade("Walk"); } else { animation.CrossFade("Idle"); }
This stops all of this if the user is not pressing this button then play idle on each check. Do it this way and you only need to write it once. :)