accessing Rigidbody2D of game object?

Hi, I have a hopefully simple question. I have a cannon ball prefab that has a Rigidbody 2D component attached to it. I also have c# script attached to my cannonBallController.

I am Instantiating the cannon ball and in the cannonBallController I can move position by using the transform.Translate just fine. But I am at a loss to access the properties of the Ridgidbody to adjust drag, gravity and such in the script?

Can someone point me to information about this or some example code?

Thanks!

[GetComponent<TComponent>()](https://docs.unity3d.com/ScriptReference/Component.GetComponent.html) will let you search for and access an instance of a component with a desired type, from the game object itself or from any other component on the same game object (such as your cannon ball controller).

var rigidbody = GetComponent<Rigidbody2D>();
rigidbody.//stuff

Edit: I should add, it has traditionally been a best practice recommendation to get and save a reference to the component in the Awake() or Start() methods, rather than calling GetComponent<T>() all the time, if you need to access the component frequently.

[RequireComponent(typeof(Rigidbody2D))]
class MyComponent : MonoBehaviour
{
    private Rigidbody2D _rigidbody;

    protected void Start()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    protected FixedUpdate()
    {
         //do stuff with _rigidbody
    }
}

I recall reading that more recent versions of Unity have attempted to optimize frequent access of other components by caching the reference, but I still follow the above pattern myself in most cases, because it clearly documents the intended usage pattern.

That worked Andy, thank you! I will alter the code to call it just once in the start function and save that as a global var.