How to Use AddForce in Unity: Simple Guide with Examples
In Unity, use
AddForce on a Rigidbody component to apply a force that moves an object physically. Call rigidbody.AddForce(Vector3 force, ForceMode mode) inside a script to push or pull the object in a direction.Syntax
The AddForce method applies a force to a Rigidbody to move it physically. It has two main parts:
Vector3 force: The direction and strength of the force.ForceMode mode(optional): How the force is applied, like a push or an instant velocity change.
Example syntax:
rigidbody.AddForce(Vector3 force, ForceMode mode);
csharp
rigidbody.AddForce(Vector3 force, ForceMode mode = ForceMode.Force);
Example
This example shows how to push a Rigidbody forward when the player presses the space key. It uses AddForce inside the Update method to apply a force continuously while the key is held.
csharp
using UnityEngine; public class AddForceExample : MonoBehaviour { public Rigidbody rb; public float forceStrength = 500f; void Update() { if (Input.GetKey(KeyCode.Space)) { Vector3 forceDirection = transform.forward * forceStrength * Time.deltaTime; rb.AddForce(forceDirection, ForceMode.Force); } } }
Output
When you hold the space key, the object with this script moves forward smoothly due to the applied force.
Common Pitfalls
- Forgetting Rigidbody: AddForce only works if the object has a Rigidbody component.
- Wrong ForceMode: Using the wrong ForceMode can cause unexpected movement. For example,
ForceMode.Impulseapplies an instant push, whileForceMode.Forceapplies continuous force. - Ignoring Time.deltaTime: Not multiplying force by
Time.deltaTimeinUpdatecan cause inconsistent force application. - Using AddForce in FixedUpdate: It's best to use
AddForceinFixedUpdatefor physics consistency, but it can work inUpdateif you multiply byTime.deltaTime.
csharp
/* Wrong way: Applying force without Rigidbody */ // This will do nothing if Rigidbody is missing // transform.AddForce(Vector3.forward * 10f); // transform does not have AddForce method /* Right way: Ensure Rigidbody and use AddForce */ Rigidbody rb = GetComponent<Rigidbody>(); if(rb != null) { rb.AddForce(Vector3.forward * 10f); }
Quick Reference
Remember these tips when using AddForce:
- Always attach a
Rigidbodyto the object. - Choose the right
ForceModefor your effect. - Use
FixedUpdatefor physics updates when possible. - Multiply force by
Time.deltaTimeif applying force inUpdate.
Key Takeaways
AddForce moves objects by applying physical forces to their Rigidbody component.
Always ensure the object has a Rigidbody before using AddForce.
Use the correct ForceMode to control how the force affects the object.
Apply AddForce inside FixedUpdate for consistent physics behavior.
Multiply force by Time.deltaTime if applying force in Update to keep movement smooth.