Simple code that has worked before, now giving error.

This is from a beginners tutorial. It worked about a year ago. I stopped using Unity for awhile and needed a refresher, but this code is not working.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{

void FixedUpdate()
{
float moveHorizontal = Input.GetAxis(“Horizontal”);
float moveVertical = Input.GetAxis(“Vertical”);

Vector3 movement = new Vector 3 (moveHorizontal, 0, moveVertical);

rigidbody.AddForce(movement);
}
}

at Rigidbody.AddForce(movement); "An object reference is required for non static field, method, or property.

I was wondering if because I am using a new version than I used to use that something has changed. I know this very simple code has worked in the past. I am also copying it directly from the tutorial.

Any help would be appreciated.

Replace ‘RigidBody.AddForce()’ by ‘GetComponent.AddForce()’. But this call isn’t free so I would cache this reference (result of ‘GetComponent’ call) and call ‘AddForce’ directly on it.

What he said.

“Rigidbody”, and a lot of other things are no longer automatically referenced, because it’s inefficient.

If you want it to act exactly like the old method that you had, you would use

GetComponent<Rigidbody>().AddForce(movement);

That is exactly what it was doing in the old version, but you didn’t see it. It’s inefficient because you should rather fetch the reference only once if you can, as opposed to fetching it every time you want to do something with it.

The correct way is to do this

public class PlayerController : MonoBehaviour
{

private Rigidbody RigidbodyComponent;

void Start()
{
    RigidbodyComponent = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");

Vector3 movement = new Vector 3 (moveHorizontal, 0, moveVertical);

RigidbodyComponent.AddForce(movement);
}
}