Unity – How to get rigidbody from object a script is applied to

April 1, 2015

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);
	}

}

ethan.york

Posts

Write for us!

We pay for great content that helps young and aspiring game makers along the path to mastery. You can earn extra income doing what you love and sharing what you learn! For more information, contact info@mastergamecraft.com.