Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Why can't I use Rigidbody2D.velocity ?

Discussion in '2D' started by iLurota, Mar 29, 2015.

  1. iLurota

    iLurota

    Joined:
    Mar 29, 2015
    Posts:
    2
    A simple question: why can't I use Rigidbody2D.velocity ? I have to use gameObject.GetComponent<Rigidbody2D>().velocity instead.
    I get the message "An object reference is required for the non-static field, method or..."
    Can anyone explain me why? Thanks in advance :)
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    RigidBody2D is the class from which objects are created. If you want to use it you need an instantiated object.

    If you are using Unity 4, you can use rigidBody2D (note the lower case r). However if you are using Unity 5, you need to use GetComponent to access it, for example:
    Code (CSharp):
    1. RigidBody2D rigidBody2D = GetComponent<RigidBody2D>();
    Some classes have static fields and/or methods, these you can access directly without creating an instance of the class. For example MathF, contains many static methods. But RigidBody2D doesn't contain any static members/functions, hence the error message.
     
    yagizozturk likes this.
  3. iLurota

    iLurota

    Joined:
    Mar 29, 2015
    Posts:
    2
    It makes sense now :D Many thanks for the reply, I'll play with it until I get the hang of it ^^