Why do I keep on getting warning NullReferenceException: Object reference not set to an instance of an object Buttons.Update ()

function Update () {
Animator.SetBool(“isRight”, isRight);
Animator.SetFloat(“speed”, speed);
Animator.SetBool(“isIdle”, isIdle);
Animator.SetBool(“isLeft”, isLeft);
Animator.SetBool(“isBack”, isBack);
if(Input.GetMouseButtonDown(0)) {
//Right Button
BlahBlah ();
hit = Physics2D.Raycast(camera.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if( hit.collider.gameObject.name == “Right”)
{
isLeft = false;
isBack = false;
isFront = false;
Debug.Log(“Clicked”);
isRight = true;
speed = 3;
isIdle = false;
}
//Left Button
if( hit.collider.gameObject.name == “Left”)
{
isRight = false;
isBack = false;
isFront = false;
Debug.Log(“Clicked”);
isLeft = true;
speed = 3;
isIdle = false;
}
}
}

I have this script which makes the character change animations like arrow keys. I keep on getting this warning NullReferenceException: Object reference not set to an instance of an object Buttons.Update () when I don’t press on any of the buttons. Why do I keep on getting this warning?

The error should give you a line number and when you double click the error, it should take you to that line in code. after that it should be pretty easy to find out what is null, and after that it’s much easier to figure out why.

Looking at the API docs of Physics2D.RayCast() it says it returns null if nothing is hit, so you should at have a null check before the collision check in both IFs at least

 if( hit != null && hit.collider.gameObject.name == "Right")