Reputation: 51
I'm an absolute beginner in programming and I'm trying my hand at Unity 5, but I get this error code whenever I try to build this code
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
Rigidbody.AddForce(movement);
}
}
I get the "error cs0120 an object reference is required for the nonstatic field method or property" can anyone help me out with this one?
Thx!
Upvotes: 2
Views: 592
Reputation: 61369
Previous to Unity 5, "rigidBody" was a property of GameObject
. Your code still wouldn't have compiled, it would have needed to be:
gameObject.rigidBody.AddForce(movement);
Because rigidBody
isn't a property or field of MonoBehavior
, gameObject
is. Since its not in Unity 5, you'll need to use GetComponent
:
RigidBody rb = GetComponent<RigidBody>();
rb.AddForce(movement);
See the documentation for more: Unity Docs
When its all said and done, the code would be:
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
RigidBody rb = GetComponent<RigidBody>();
rb.AddForce(movement);
}
Upvotes: 1