How to lock the rotation of an Object

I need the lock the rotation of the player object being controlled, and other answers I have found have not been working. I made a new script just for locking the rotation. My other script only controls the X and Y axes, and doesn’t modify the rotation at all, and I would like a C# script line that will lock the object’s rotation to one value, and will not change, even if there is another object bumping into it.

2 Likes

3 Answers

3

This is one way to do it:

using UnityEngine;
public class helpscript : MonoBehaviour
{
	public float fixedRotation = 5;
 	void Update ()
	{
		Vector3 eulerAngles = transform.eulerAngles;
		transform.eulerAngles = new Vector3( eulerAngles.x , fixedRotation , eulerAngles.z );
	}
}

This method worked for me as my object was an empty gameobject functioning as a pivot, and it wouldn't work (or make sense) to add a rigidbody to it. Thanks for the help!

wouldn't this affect the performance if we are going to be setting this for every frame? Also, I found that a better was to control an object's rotation is to directly use transform.rotation or transform.localRotation localRotation:https://docs.unity3d.com/ScriptReference/Transform-localRotation.html rotation : https://docs.unity3d.com/ScriptReference/Transform-rotation.html Playing around with these should work.

It sounds to me like “Freeze Rotation” on the rigidbody would fix this.

LOL Thank you so much, I don't know how I missed that XD

For an alternate solution to the answer, you can lock rotation every frame by using. Freeze Rotation probably works better for performance on rigid bodies.

void Update ()
{
    transform.rotation = Quaternion.identity;
}