New to Coding with c#

I’m trying to complete one of the tutorial projects and have been following it to a ‘T’ but when I went to incorporate my code into the sphere I’d created it says there is a problem in the code and I can’t figure out how to fix it. Now I’m sure it’s something super simple but being I have very little experience as to what I’m doing I could use a pointer as to how to fix this problem.

This is what it is telling me when I debug…

An object reference is required for the non-static field, method, or property ‘UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3)’

using UnityEngine;
using System.Collections;

public class Player_Controller : MonoBehaviour
{
void FixedUpdate (){
float moveHorizontal = Input.GetAxis (“Horizontal”);
float moveVertical = Input.GetAxis (“Vertical”);

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

Rigidbody.AddForce (movement);
}
}

http://unity3d.com/search?gq=“An%20object%20reference%20is%20required%20for%20the%20non-static%20field%2C%20method%2C%20or%20property”

You can’t call RigidBody.AddForce directly because AddForce is a function in the RigidBody class, you need to create a variable/object of type RigidBody and call AddForce through the variable. For example this script (this assumes the rigidbody is on the same game object as this script)

Rigidbody rb; //first create a variable of the desired type, in this case RigidBody

void Start()
{
    rb = gameObject.GetComponent<RigidBody>(); //intialize the variable
}

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

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    rb.AddForce(movement); //call the function through the variable
}

So every time you get the message that an object reference is required, you need to make an object (variable of a certain type) and access whatever you’re trying to access through the variable/object.

1 Like

The error is stating that the ‘Rigidbody.AddForce’ is being called as a static method, but AddForce needs to be called from an Rigidbody object instance.

Something like:

// We need a Rigidbody instance to work with.
// Assign rb to the current game object's Rigid Body component
// (make sure the game object has a rigid body component before running)
Rigidbody rb = GetComponent<Rigidbody>();
rb.Rigidbody.AddForce(movement);

Replace your original AddForce method call with these lines.

[Edit]
@willemsenzo beat me to it. Do it his way, as it caches the rigid body at the start, while my simple to read way gets the rigid body reference each frame, costing a bit more time per frame.

In unity 4.x you could use rigidbody (small r) to access the attatched Rigidbody. From 5.0 onwards you must use GetComponet() instead.

Proper case is a big issue.

Thank you guys so much, you’re all awesome. It works.