Address
304 North Cardinal St.
Dorchester Center, MA 02124

Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM

Unity how to lock rotation

Unity How to lock rotation

On Unity, we’ll look at how to lock the rotation of a physical object in 2D and 3D.
Since it’s a physical object, it will have the Rigidbody2D component for 2D and the Rigidbody component for 3D.

Lock rotation of an 2D object

To lock the rotation of a 2D object, you need to check “Freeze Rotation” in the inspector or set the “freezeRotation” property to true in the code:

Unity lock rotation 2D
using UnityEngine;

public class FreezeRotation2D : MonoBehaviour
{
    public Rigidbody2D rigidbody2dRef;

    private void Start()
    {
        rigidbody2dRef.freezeRotation = true;
    }
}

Lock rotation of an 3D object

To lock a 3D object’s rotation, you need to check the “X“, “Y” and “Z” of the “Freeze Rotation” field in the Inspector, or set the “freezeRotation” property to true in the code:

Unity lock rotation 3D
using UnityEngine;

public class FreezeRotation3D : MonoBehaviour
{
    public Rigidbody rigidbodyRef;

    private void Start()
    {
        // freeze all rotation
        rigidbodyRef.freezeRotation = true;
        // or 
        rigidbodyRef.constraints = RigidbodyConstraints.FreezeRotation;

        // freeze X
        rigidbodyRef.constraints = RigidbodyConstraints.FreezePositionX;

        // freeze x & y
        rigidbodyRef.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY;
    }
}

It’s a little different from 2D, because here you can freeze one or more angles.

You can define the angle to freeze directly using the RigidbodyConstraints enum, or if you want several constraints, you can add them one after the other, separated by “|”.

Note that the “constraints” property can also locks the position.

I hope this has helped you, now you know how to lock rotation in Unity.

Learn More

Have you just started your Unity adventure?
I recommend this article to get you started in the best possible way: The Best Advice I Wish I Had When I Started Game Development

Check our other articles about Unity:

Leave a Reply

Your email address will not be published. Required fields are marked *