- Home /
NullReferenceException when trying to animate sprite
Hello,
I have been trying to animate a sprite. I have some animations set up, added an animation controller to my object and configured the controller in the animator tab, but when I try to change the value of my State Parameter, the following error shows:
NullReferenceException: Object reference not set to an instance of an object
Here is the code where I am trying to change the animation:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
Animator animator;
public KeyCode left;
public KeyCode right;
// Use this for initialization
void Start () {
}
void FixedUpdate () {
if (Input.GetKey (left)) {
animator.SetInteger ("State", 2);
}
if (Input.GetKey (right)) {
animator.SetInteger ("State", 2);
}
}
}
I am trying to change the value of State to 2, which should trigger the transition to my "run" animation.
Answer by zach-r-d · Jun 20, 2015 at 08:46 PM
The Animator animator;
variable is never being set, so it's staying at its default value of null, and when a method is called on null it results in a NullReferenceException. Try putting this in the Start() method to set the variable to the Animator attached to the same GameObject:
animator = GetComponent<Animator>();
After putting this code in the Start function, it has stopped the errors from showing, but my sprite doesn't change animations. I have double-checked the animator file to make sure the transitions are set up, but nothing happens when I try to change the value of State.
Could you post a screenshot of the Parameters tab of the animator controller in question?
Thanks for the reply.
That stops the errors from showing, but when I write animator.SetInteger ("State", 2);
, it does not switch animations.
I have double-checked the animator controller file, and it is set to change when State equals 2. In the tutorials I have looked at, this seems to work fine, so I'm not sure what I'm doing wrong.
There are a number of things that could be going wrong. Posting a screenshot of the Parameters tab will significantly help with diagnosing the problem.
Whoops, just found the problem. It seems like I had misconfigured the animator file and gotten the State values mixed up.
Thanks for helping me solve the problem guys.
Your answer
Follow this Question
Related Questions
2D Sprite, Animation Question 1 Answer
A little question about sprites and RAM on a specific device?? 1 Answer
why is my Gun Model Only rendering the front bit when the animations are on? 2 Answers
How do you create an animated texture for a UV'd Mesh and apply it? 1 Answer
what cause 'error dt >= 0'? 3 Answers