How to Add Force in Unity: Simple Rigidbody Example
In Unity, you add force to an object by calling
Rigidbody.AddForce(Vector3 force) on its Rigidbody component. This method applies a force vector that moves the object physically in the game world.Syntax
The basic syntax to add force in Unity is:
rigidbody.AddForce(Vector3 force, ForceMode mode = ForceMode.Force);Here:
rigidbodyis the Rigidbody component attached to your game object.Vector3 forceis the direction and strength of the force.ForceMode(optional) defines how the force is applied (default isForce).
csharp
rigidbody.AddForce(Vector3 force, ForceMode mode = ForceMode.Force);
Example
This example shows how to add a forward force to a Rigidbody when the space key is pressed. It moves the object forward smoothly.
csharp
using UnityEngine; public class AddForceExample : MonoBehaviour { private Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { if (Input.GetKeyDown(KeyCode.Space)) { Vector3 forceDirection = transform.forward * 500f; rb.AddForce(forceDirection); } } }
Output
When you press the space key, the object moves forward with a sudden push.
Common Pitfalls
Common mistakes when adding force in Unity include:
- Not having a Rigidbody component on the object, so
AddForcedoes nothing. - Using very small force values that don't move the object noticeably.
- Forgetting that
AddForceis affected by mass and drag of the Rigidbody. - Using
AddForceinUpdate()instead ofFixedUpdate()for physics consistency.
Always check your Rigidbody setup and apply forces in FixedUpdate() for smooth physics.
csharp
/* Wrong: Adding force in Update() repeatedly */ void Update() { rb.AddForce(Vector3.forward * 10f); } /* Right: Adding force once or in FixedUpdate() */ void FixedUpdate() { if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(Vector3.forward * 500f); } }
Quick Reference
Tips for adding force in Unity:
- Use
Rigidbody.AddForce()to move objects physically. - Choose
ForceModebased on effect:Force,Impulse,VelocityChange, orAcceleration. - Apply forces in
FixedUpdate()for stable physics. - Ensure the object has a Rigidbody component.
Key Takeaways
Use Rigidbody.AddForce with a Vector3 to apply physical force to objects.
Apply forces inside FixedUpdate() for consistent physics behavior.
Ensure your object has a Rigidbody component before adding force.
Adjust ForceMode to control how the force affects the object.
Small forces or missing Rigidbody cause no visible movement.