Following 2D character Controller tut but getting nullreference

Hi guys,
I’ve just started using Unity2D and my first foray into C sharp.
I’m currently following the 2D character controller tutorial on the site and as my usual luck things break even when I’m absolutely confident I’ve done nothing wrong. >_>

Portion of code below:

public class CharacterControl : MonoBehaviour
{
public float maxSpeed = 5.0f;
bool faceRight = true;
Animator anim;
// Use this for initialization
void Start ()
{
anim.GetComponent<Animator> ();
}

// Update is called once per frame
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
anim.SetFloat ("Speed", Mathf.Abs (move));
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);

At line 6 after building it states that the Field ‘CharacterControl.anim’ is never assigned and will always return null…

So apparently it doesn’t notice line 16 or I’m missing something… >_>

I’ve checked a second tutorial and it does things exactly the same way.
When I run the code the error it throws at me is

NullReferenceException: Object reference not set to an instance of an object
CharacterControl.FixedUpdate () (at Assets/Scripts/CharacterControl.cs:23) (It’s line 23 for me cause I’ve cut the first few lines out)

I may not be the worlds best programmer but I’m pretty confident code shouldn’t break when it’s word for word to someone elses code that’s practically copy and paste bar some variable and function name changes.

Any help would be appreciated, thanks.

do you have add Animator, to the object, where this controller script is ?

if you will just move your object, just delete 5, 9, 16 lines.

if move with change animation from idle to run (or something), then add Animator and make boolean “Speed” in animator window.

ps. sorry, “speed” must be float

Both the animator and script is assigned to the character.
I have a transition from idle to run animations set.
I can move the character around by commenting out line 16 but put it back in and the character refuses to move while still playing the idle animation.
I’ve checked the run animation and that does work when set to default.
I’ve tried changing the Speed parameter but it doesn’t work.
Haven’t tried bool rightly enough yet though, I’m at work so will have to try when I get home.

I’m pretty sure it has nothing to do with the parameter as I’ve tried different things with line 16 and it gives me the same error.

sorry, “Speed” must be float.

  • anim.GetComponent ();

this line must be:

anim = GetComponent ();

Ok, if that’s the case then nothing changes in regards to the error. I’ve not been home to change my speed parameter which is still originally a float anyway.
Sytanx wise everything is ok them I assume?

i have edited, try this at 9 line:

anim = GetComponent ();

Oh my God! That works!
I’m an idiot >_<
Thanks very much.
Now time to slap myself a hundred times for not noticing that.