Unity how to lock rotation

Unity How to lock rotation

As usual on Unity, properties can be modified by code or using the Inspector.
To lock a rotation, we’ll need to use the properties of the Rigidbody2D or Rigidbody components.

Lock rotation of an 2D object

In the 2D world, a rotation is locked using “Freeze Rotation” in the Inspector or “freezeRotation” 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;
    }
}

The interface is different on Rigidbody, because unlike 2D, several angles can be locked.

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.

Leave a Reply

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