Rotate a GameObject from a script
Rotate GameObjects with transforms from scripts.
Read time 2 minutesLast updated 6 days ago
Internally, Unity stores every rotation as quaternion while the Transform component Inspector displays rotation as Euler angles. You can use both Euler angles and quaternions to represent rotations and orientation. These representations are equivalent but have different uses and limitations. Still, Unity converts Euler angles values from the Inspector to a quaternion. The reason is that Euler angles might cause gimbal lock and quaternions avoid it.
To learn more about , refer to Controlling rotation with the Quaternion class
QuaternionEuler angles
When you set or , Unity doesn't store the X, Y, and Z values. It converts them to a quaternion and stores that in or . When you read either property, Unity converts the quaternion back to Euler angles. Because more than one set of Euler angles can describe the same rotation, the values you read can differ from the values you assigned.
Transform.eulerAnglesTransform.localEulerAnglesTransform.rotationTransform.localRotationFor example, if you set a rotation to (150, 35, 45), reading it back returns (30, 215, 225). This describes the same rotation. Unity treats angles modulo 360°, so , , and all produce the same angle. The values of can also differ from the Inspector, because is in world space, while the Inspector displays local rotation. To avoid unexpected results, don't read, modify, and write back Euler angles. Keep the angles in your own variables and apply all three at once.
1361-17999Transform.eulerAngleseulerAnglesModify rotations
The following example limits how far a GameObject can turn around its y-axis. It stores the angle in a variable instead of reading , uses the method to keep the angle between 0° and 100°, and then applies the angle with the method.
transform.eulerAnglesMathf.ClampQuaternion.Eulervoid ClampGameObjectRotation(float turnInput) { //Multiply by Time.deltaTime so the GameObject rotates at turnSpeed units per second, at any frame rate. yAngle += turnInput * turnSpeed * Time.deltaTime; // Keep the angle between 0 and 100 degrees. yAngle = Mathf.Clamp(yAngle, 0, 100); // Quaternion.Euler converts angles in degrees to a Quaternion. transform.localRotation = Quaternion.Euler(0, yAngle, 0); }