Search Unity

Error with some simple sprite movement with Rigidbody2D

Discussion in '2D' started by Sixoul, Jan 14, 2014.

  1. Sixoul

    Sixoul

    Joined:
    Jan 9, 2014
    Posts:
    20
    I've been getting this error
    Code (csharp):
    1. An object reference is required for the non-static SerializeField, method, or property 'UnityEngine.Rigidbody2D.velocity.get'
    for this code
    Code (csharp):
    1.         if (Input.GetKey(moveUp))
    2.         {
    3.             animator.SetInteger("Direction",2);
    4.             Rigidbody2D.velocity = new Vector2(0, speed);
    5.         }
    I'm trying to make the character move using rigidbody2D. All I know is I need to put something before rigidbody2D. Like gameObject.Rigidbody2D.velocity or something. But I know gameObject doesn't work. I'm pretty sure what I do need to put references the object that the script will be controlling. So what am do I need to put?

    Am I going about this the right way? I'm sure there's better cleaner and more efficient ways to go about this but I'm just keeping it simple for now.
     
  2. RedVonix

    RedVonix

    Joined:
    Dec 13, 2011
    Posts:
    422
    The right code actually does use gameObject. Try this:

    Code (csharp):
    1.  
    2. gameObject.GetComponent<RigidBody2D>().velocity = new Vector2(0, speed);
    3.  
     
    Last edited: Jan 14, 2014
  3. Sixoul

    Sixoul

    Joined:
    Jan 9, 2014
    Posts:
    20
    Oh. gameObject made sense to me so that's what I thought. I was close. Thanks for the help.

    But even after making those changes the sprite doesn't move around. Speed is a float set to 10 so it should be doing something right?
     
  4. unitylover

    unitylover

    Joined:
    Jul 6, 2013
    Posts:
    346
    You capitalized the r in Rigidbody2d so Unity thinks you're trying to access the Rigidbody2D class which you are not. You can reference the rigidbody attached to your gameobject by simply going:

    Code (csharp):
    1.  
    2. rigidbody2D.velocity = new Vector2(0, speed);
    3.  
     
  5. Sixoul

    Sixoul

    Joined:
    Jan 9, 2014
    Posts:
    20
    oh ok. That's gonna be a little annoying until I get use to all the classes and methods. Thanks, that did the trick.
     
  6. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,550
    Just think of it like this, if it's a property/variable, it starts lower-cased, if it's a Component/Method/Object, it starts capitalized.
     
  7. dasbin

    dasbin

    Joined:
    Jan 14, 2012
    Posts:
    261
    In general you can just think of capitalized objects as classes or methods, and lower-case objects as variables.

    Keep in mind the rigidbody variable reference is not set - Unity actually looks it up every single time it is called. So performance-wise it is actually better to cache it once yourself before you need it and refer to your cached reference when you need it, not rigidbody.