Spent a fair bit looking for the answer to this question online and eventually I just mashed at the keyboard until something worked. It ended up being way simpler than I’d originally thought, but I figure the next poor soul who wants to do this won’t have to look as hard now. Here’s a simple MonoBehaviour which will prevent the rotation about the x and z axes in the editor:
using UnityEngine;
[ExecuteInEditMode()]
public class PreventRotateXZ : MonoBehaviour
{
public void Update ()
{
if(!Application.isPlaying)
{
// prevent rotation about x and z axes
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
}
}
}
As a side note, it’d be prettier if I had a way to disable the x and z axis rotation discs on the rotation tool; I couldn’t find a way to do that.
Fairly old but, this above code does not work correctly, because the editor already transformed the object, than you try to prevent the finished rotation. So it end up in chaotic rotations or movements.
There was no real working solution in the unity forum that locks any rotation axis well.
I found solution by my self to lock a rotation axis in the editor. You can also lock any position and reset the rotation from the first instantiate.
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode]
[SerializeField]
public class LockRotationPosition: MonoBehaviour {
private Vector3 lockPosition = Vector3.zero;
private Quaternion lockRotation = Quaternion.identity;
public bool resetRotation = false;
public Vector3 defaultRotation = Vector3.zero;
[Space(4)]
public bool XRotationLock = true;
public bool YRotationLock = false;
public bool ZRotationLock = true;
public bool XPositionLock = false;
public bool YPositionLock = false;
public bool ZPositionLock = false;
#if UNITY_EDITOR
void Update() {
if (!Application.isPlaying) {
if (Tools.current == Tool.Rotate) {
transform.position = lockPosition;
var rot = transform.eulerAngles;
if (XRotationLock) rot.x = lockRotation.eulerAngles.x;
if (YRotationLock) rot.y = lockRotation.eulerAngles.y;
if (ZRotationLock) rot.z = lockRotation.eulerAngles.z;
transform.eulerAngles = rot;
} else if (Tools.current == Tool.Move) {
var pos = transform.position;
if (XPositionLock) pos.x = lockPosition.x;
if (YPositionLock) pos.y = lockPosition.y;
if (ZPositionLock) pos.z = lockPosition.z;
transform.position = pos;
}
lockPosition = transform.position;
lockRotation = transform.rotation;
}
}
void OnEnable() {
if (!Application.isPlaying) {
lockPosition = transform.position;
lockRotation = transform.rotation;
}
}
void OnValidate() {
if (resetRotation) {
transform.eulerAngles = defaultRotation;
resetRotation = false;
}
}
#endif
}
I use this script to prepare direction markers in editor to define wave direction coming for the water tesselation for my new water asset.
1 Like