'An object reference is required for the non-static field, method, or property' error

This error only shows up when I use Rigidbody. It occurs in the rotate and move section at the bottom. I’ve put in my code below so is there a way to get past this?

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
private Animator anim; // Reference to the animator component.
private int stateIsRunning; // Reference animator’s “IsRunning” var.

private float turnSpeed = 360f; // Angle in degrees user can turn per second.
private float angleFacing = 180f; // Angle user is currently facing.
private float turnSmoothing = 100.0f; // A smoothing value for turning the player.
private float runSpeed = 0.02f; // Speed of players run.

void Awake () {
anim = GetComponent();
stateIsRunning = Animator.StringToHash(“IsRunning”);
}

void FixedUpdate () {
float h = Input.GetAxis(“Horizontal”);
float v = Input.GetAxis(“Vertical”);
MovementManagement(h, v);
}

void Update () {
}

void MovementManagement (float horizontal, float vertical) {
// Animation:
if (vertical > 0) { // Will eventually want different animation for backwards.
anim.SetBool (stateIsRunning, true);
} else {
anim.SetBool (stateIsRunning, false);
}

// Rotate:
angleFacing += (horizontal * turnSpeed * Time.deltaTime);
float rad = Mathf.Deg2Rad * angleFacing;
Vector3 targetDirection = new Vector3(Mathf.Sin(rad), 0f, Mathf.Cos(rad));
Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
Quaternion newRotation = Quaternion.Lerp(Rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);
Rigidbody.MoveRotation(newRotation);

// Move:
float moveAmount = vertical * runSpeed;
Vector3 newPos = Rigidbody.position;
newPos.x += (Mathf.Sin(rad) * moveAmount);
newPos.z += (Mathf.Cos(rad) * moveAmount);
Rigidbody.MovePosition(newPos);
}
}

Don’t forget to use code tags Using code tags properly

Next, RigidBody must be accessed through GetComponent, just like all the other components. Long ago Unity allowed you to access it directly with RigidBody, but this is no longer the case.

Just to add to what @Brathnann said:

Under this line of code:

private Animator anim; // Reference to the animator component.

Add this:

Rigidbody rb;

And in Awake()

rb = GetComponent<Rigidbody>();

Then, switch your previous “Rigidbody” parts of code to ‘rb’.

Added, just in case the OP wasn’t sure what that was, yet.

1 Like

Thank you, it worked :). How do I mark this question answered?

Cool, glad it’s working for you. Nothing is really marked ‘answered’ here, beyond you saying so :wink: