- Home /
How to play animation on keypress
I gave this script to my player, but when I press the button it says NullReferenceException
var dance : AnimationClip;
function Update ()
{
if(Input.GetKeyDown(KeyCode.B))
{
animation.Play("Dance", PlayMode.StopAll);
}
}
Have you attached an animation component to your gameObject?
it gave you a call stack with that presumably? check if animation is null - otherwise somthing else is wrong - perhaps the Dance animation is missing? also, why is there a variable 'dance' here? you are not using it in the code you provide...
Yes, it gave me a call stack, I have the dance animation in my project and scene, and I added the variable dance just incase I wanted to change the animation in project view ins$$anonymous$$d of going into the script.
what was the call stack?
this is often useful information. sorry but i don't trust you to have not included it with good reason - i have no idea what your thought process is.
the fact that a keypress is involved here is completely unimportant so I also have a measurable bit of evidence in the question title that suggests I can not trust that you did not include it with good reason.
there is a small probability that someone can tell you precisely the problem simply by inspecting the call stack.
Answer by thornekey · Jan 12, 2014 at 04:35 PM
give your player the animation component. and make sure the animation file is called "Dance"
Answer by semiessessi · Jan 12, 2014 at 06:56 PM
Assuming that the file this code is in is called 'Player Functions.js' then the problem is that animation is null when the code is being called.
Wherever you are initialising it with 'GetComponent' is either failing because the component is not attached or there is no such call being made. Whatever the case the 'animation' variable is not being initialised correctly or at the right time. The solution would be something to ensure that there is something like this in your class definition:
var animation : Animation;
and something like this in your Awake or Start function:
animation = gameObject.GetComponent( Animation );
Its a shame that the Unity documents do not include the required boilerplate in their examples - if you follow them naively then you would try and use animation without ever declaring it or initialising it, which I suspect is what you have done. (for example see the documentation for Animation.Play)