Lock the rotation of an Object in Unity

Hello Game Developers, In this article, I will show how to “Lock the rotation of an Object in Unity”.

During game development, this simple object rotation issue in 3D games has been encountered by many game developers. The item rotates while moving or after the collision, which is not necessary. To prevent that we can lock the rotation of the object.

Let’s discuss how to implement it.

Transform.eulerAngles

eulerAngles stores the rotation of a GameObject relative to the world coordinate system in the form of a Vector3 structure.

eulerAngles property is used to set rotation of a GameObject relative to the world coordinate system.

eulerAngles property is used to rotate a GameObject relative to the world coordinate system.

Procedure

To lock the rotation of an object we need to provide a fixed rotation

  1. Create a C# code
  2. Name it as RotationController
  3. Add this C# script to GameObject
  4. Write down the script given below
  5. In this script, we will give the fixed rotation = 180
  6. The GameObject’s  rotation will be  fixed at 180 degree

C# Code: Lock the rotation of an Object in Unity

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotationController : MonoBehaviour {

    Transform r;
    public float fixedRotation = 180;

     void Start () {
        r = transform;
    }
    
     void Update () {
        r.eulerAngles = new Vector3 (r.eulerAngles.x, fixedRotation, r.eulerAngles.z);
    }
}

Leave a Reply

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