Rigidbody2D.velocity Help

Hi all,

I have been following the tut at:
http://unity3d.com/learn/tutorials/modules/beginner/2d/2d-controllers
but it seems to include code for an older unity version.

I tried correction code as much as I could with what I have read around but am still getting err at 20 of “An object reference is required for the non-static field, method, or property ‘UnityEngine.Rigidbody.velocity.get’ (CS0120).”

TY!

using UnityEngine;
using System.Collections;

public class NorrisControllerScript : MonoBehaviour
{

   public float maxSpeed = 10f;
   bool facingRight = true;

   // Use this for initialization
   void Start () {
   
   }
   
   // Update is called once per frame
   void FixedUpdate ()
   {
     float move = Input.GetAxis ("Horizontal");
     GetComponent<Rigidbody>().velocity = new Vector2(move * maxSpeed, Rigidbody.velocity.y);
     if (move > 0 &&!facingRight)
       Flip ();
     else if (move < 0 && facingRight)
       Flip ();
   }
   void Flip()
   {
      facingRight = !facingRight;
      Vector3 theScale = transform.localScale;
      theScale.x *= -1;
      transform.localScale = theScale;
   }}

You are trying to access the “velocity” variable of the Rigidboy class, not the rigidbody component. That’s what the error is telling you: you are trying to access a non-static field (if you are unsure what static means, read about it here) on the class itself, instead of on an object instance. In previous versions of Unity, you could use “rigidbody”, with a lower case letter, to access the Rigidbody component that’s attached to the same GameObject as your script is (same goes for a whole lot of other components). In Unity 5, this behaviour still exists for legacy, but is considered deprecated.

So, you need to do the following:

Rigidbody rigidbody = GetComponent<Rigidbody>();
rigidbody.velocity = new Vector2(move * maxSpeed, rigidbody.velocity.y);

Ah okay TY! I will certainly read up on static.

So the script compiles with no bugs, thankfully. But now I get an error when playing the scene"

“MissingComponentException: There is no ‘Rigidbody’ attached to the “Character” game object, but a script is trying to access it. You probably need to add a Rigidbody to the game object “Character”. Or your script needs to check if the component is attached before using it.”

Its pretty self explanatory, and I do have a Rigidbody2d on my Sprite’s inspector. Should I have included 2d somewhere in the script? Unfortunately, this is the first script I have played with, and I am still very new to it. :frowning:

Yep, just use GetComponent() instead.

That did it. Thx guys!
Rigidbody2D rigidbody = GetComponent();