Object reference not set to an instance of an object

I am doing a simple walk animation by following a tutorial he moves but the walk animation does not play due to the Object reference not set to an instance of an object error popping up for line 33 so the error is occurring in the if else statement but i cant figure out why. The boolean “isWalking” has been created in parameters and is set to the transition both ways.

using UnityEngine;
using System.Collections;

public class malccontrols : MonoBehaviour {
static Animator anim;
public float speed = 10.0F;
public float rotationSpeed = 100.0F;

// Use this for initialization
void Start () {

    anim.GetComponent<Animator>();

}

// Update is called once per frame
void Update () {

    float translation = Input.GetAxis("Vertical") * speed;
    float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
    translation *= Time.deltaTime;
    rotation *= Time.deltaTime;
    transform.Translate(0, 0, translation);
    transform.Rotate(0, rotation, 0);

    if (translation != 0)
    {
        anim.SetBool("isWalking", true);
    }

    else
    {
        anim.SetBool("isWalking", false);
    }

}
}

There is no code that actually sets the variable “anim” to any value, so it remains null.

Actually, you should already have gotten an error in line 11 when you start the game, as Start() also accesses anim.

You probably meant to write “anim = GetComponent()” in Start() and not “anim.GetComponent()” (at least if you meant to add this script to the gameObject that also holds the Animator component)

Also, why do you make “anim” static? This way, it is shared between ALL scripts of the same type.

If you have every only one script of type “malccontrols”, the static is unnecessary. You should still considering make it non-static, so it will still work when you do an assembly reload during gameplay (and also to inspect it in debug-mode of the inspector).

If you have more than one script of type “malccontrols” on different gameObjects and they have each an own Animator, then you need to remove the static to get this to work. You don’t want to share the value.

Finally, if you have more than on script “malccontrols” but only one “Animator” and are the malccontrols are supposed to work on the same shared Animator, then you might still remove the static and set it for each malccontrols seperately (for the assembly-reload and Debug-inspector reasons). But this last case could be… maybe… a case where “static” is fine. Anyway, in that case you have to know find and initialize the shared “anim”.