how to play an animation by pressing a key

when ever i try to put an animation in the inspector
This is what i have.

1.)var PowerOn : Animation;
2.)
3.)function Start () {
4.)
5.)}
6.)
7.)function Update(){
8.) if(Input.GetKeyDown(KeyCode.F)){
9.) this.animation.Play(“Power On”);
10.) }
11.)}

in the inspecter this is what it shows:

Turn On Power(Script)
Script jsTurnPowerOn
Power On none(Animation)

when ever i bring the animation i have, or any other animation, and drag it on top it wont let me it has the circle with the line through it how do i make it so i can add an animation.

1 Answer

1

var PowerOn : AnimationClip;

function Start() {

}

function Update() {
   if( Input.GetKeyDown(KeyCode.F) ) {
      animation.Play(PowerOn);
   }
}
  1. You should use AnimationClip instead of Animation
  2. this.animation is redundant, just use animation
  3. animation.Play("PowerOn") will play the PowerOn animation included in the gameObject, not the PowerOn animation you assign in the inspector. Use animation.Play( animationClipVariable) instead of animation.Play("animationStringName")

Last but not least, use the

101 
010

button on the top to format your code, it should be the fifth button from left.

One more thing, even though PowerOn is technically a okay way to name variables, the better way to do it is powerOn. You can differentiate the name in your script very quickly: Class Class.StaticFunction() variable variableWithLongerNames variable.Function() variable.FunctionWithLongerName() Function and class should be fully capitalized, while variable should be using a camel style: capitalize all but the first word