Object reference not set to an instance of an object (Unity 2D animation)
Hey guys, I'm currently trying to figure out how to Animate in Unity 2D and with that I stumbled into transitioning. Although I have no idea how to call the transition parameters into code, this is my current attempt which is giving the error above. I dont know why Its giving me the error as in Start() I called the animator component into the script. (full error: NullReferenceException: Object reference not set to an instance of an object MovementFixed.Update () (at Assets/Script/MovementFixed.cs:21) ) Any help would be great! Thanks!
Animator animator;
public float speed = 1.5f;
public int Direction = 0;
void start(){
animator = this.GetComponent<Animator>();
}
void Update ()
{
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.position += Vector3.left * speed * Time.deltaTime;
animator.SetInteger("Direction", 1);
}
if (Input.GetKey (KeyCode.RightArrow)) {
transform.position += Vector3.right * speed * Time.deltaTime;
animator.SetInteger("Direction", 1);
}
if (Input.GetKey (KeyCode.UpArrow)) {
transform.position += Vector3.up * speed * Time.deltaTime;
animator.SetInteger("Direction", 1);
}
if (Input.GetKey (KeyCode.DownArrow)) {
transform.position += Vector3.down * speed * Time.deltaTime;
animator.SetInteger("Direction", 1);
}
}
}
Answer by nullpainter · May 25, 2017 at 09:44 AM
This is a regular C# error where a variable hasn't been initialised before it's being used. In this case, it's because your Start() method is called start() and therefore isn't being called by Unity. C# is case-sensitive.
Because of this, your animator variable hasn't been initialised, so explodes the first time you try to use it.
Rename it to Start() and the problem should go away.
Your answer
Follow this Question
Related Questions
2D Animation Delay 3 Answers
8-way 2D top down movement (diagonal) idle animation issues 0 Answers
Transitioning between 2D animations by frame 2 Answers
Animation location problem! 0 Answers