Documentation

Unity Engine

Download Unity

Unity Engine

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
Quaternion
, refer to Controlling rotation with the Quaternion class

Euler angles

When you set
Transform.eulerAngles
or
Transform.localEulerAngles
, Unity doesn't store the X, Y, and Z values. It converts them to a quaternion and stores that in
Transform.rotation
or
Transform.localRotation
. 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.
For 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
1
,
361
, and
-17999
all produce the same angle. The values of
Transform.eulerAngles
can also differ from the Inspector, because
eulerAngles
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.

Modify 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
transform.eulerAngles
, uses the
Mathf.Clamp
method to keep the angle between 0° and 100°, and then applies the angle with the
Quaternion.Euler
method.
void 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); }

Additional resources