Unity - How to Get Rigidbody From Object a Script Is Applied To

Here’s how to get the rigidbody from an object the script is applied to in Unity. The example shown is in C#.

using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { private Rigidbody rb; // Use this for initialization void Start () { rb = GetComponent (); } // Update is called once per frame void Update () { } // Called before any physics calculations. // This is where you put your physics code. // We apply forces to the rigid body, which is physics, so this is where it goes. void FixedUpdate() { // Pressing arrow keys on keyboard will apply force to rigidbody float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical); rb.AddForce (movement); } }