Skip to main content
Updated date:

How to Rotate Objects in Unity

Author:

Matt Bird writes all sorts of nonsense, but he enjoys writing tutorials for Unity.

There are many reasons you might rotate an object in Unity. Maybe a door needs to swing on a pivot point, or an enemy needs to spin in a particular way as they fly through the air, or, most likely, a character may need to turn when moved. Rotation is useful for 2D and 3D games alike, and having at least a grounding in how to do it is wise.

There are, in general, three different ways to rotate an object in Unity.

Screenshots taken by myself. Unity owned and developed by Unity Technologies.

Screenshots taken by myself. Unity owned and developed by Unity Technologies.

Method 1: Rotate in Scene View

Have a look at the screenshot above. Here we have an object on a 3D plane in the Scene View window. Normally when you select an object, it will have guidance arrows that allow you to move it around, but right now, it has three rings around it. If you click on the Rotate Tool in the top-left corner of the screen - it's a pair of arrows formed into a circle - the rings will appear, allowing you to rotate the object freely. Set it however you like.

The red ring will change the object's x-axis orientation; the green ring will change the object's y-axis orientation, and the blue ring will change the object's z-axis orientation.

how-to-rotate-objects-in-unity

Method 2: Rotate via the Inspector

The second method is to change the GameObject's Rotation values. Click on the object and look at the Inspector on the right. The top component, Transform, has three Rotation values for x, y, and z. Entering numbers into these fields will change the rotation of the GameObject in the Scene view.

(Messing with the rotation of an object can get messy at times, so if you ever want to start from square one, simply change all three values to zero.)

While we are in the Inspector, it is worth noting that these values only capture the rotation of the GameObject on a global perspective. If the GameObject is childed to another GameObject its Rotation values reflect its rotation relative to its parent. So if the parent is rotated and the child object is rotated with it, the child's Rotation values will initially appear as 0, 0, and 0.

The following two methods are only useful for rotating GameObjects outside of runtime. If you want to rotate objects during runtime, you'll need to do some coding.

Method 3: Rotate via Code

A simple rotation effect is pretty easy to achieve while programming and requires only a single line of code to put into effect. It goes like this:

 if(Input.GetKeyDown(KeyCode.B))
        {
            itemToRotate.transform.Rotate(45f, 45f, 0f, Space.Self);
        }

In this case, we have a GameObject, itemToRotate, and we want to set it at 45-degree angles. We access the GameObject's Transform and use the Rotate function to set its three euler values. There is also a setting for the GameObject's relativity, which brings us back to local and world space. If you want the object to rotate relative to the world, use Space.World; if you want the object to rotate relative to itself, use Space.Self.

This code will quickly and painlessly rotate the GameObject. In most cases, however, this is not the code you want to use, because it is instantaneous. In order to see the GameObject actively rotate, you'll want to try something like this:

private void Update()
 {
	if (Input.GetKeyDown(KeyCode.B))
	        {
	            rotateObjectBool = true;
	        }
	
	if(rotateObjectBool)
	        {
			   	rotationTime = 180f;
		        itemToRotate.transform.Rotate(Vector3.down * (rotationTime * Time.deltaTime));
	        }
}

Here we use a simple bool trigger, rotateObjectBool, to set the rotation in motion. When the player hits the B key itemToRotate begins to rotate along a Vector3 over time. Time.deltatime measures the amount of time since the last frame, so multiplying a value by Time.deltatime will give you a nice, real-time rotation. Changing the rotationTime variable will speed up (higher value) or slow down (lower value) the rotation speed.

Vector3.down will decrease the object's y value over time. if you use Vector3.up instead it will increase the object's y value and spin it in the opposite direction. Vector3.right and Vector3.left have a similar effect on the object's x value. If you want you can have lines that affect both the x and y values simultaneously, making for a neat spinning effect.

These Vector3 variables are all well and good when you want an object to spin freely forever. Update will keep them going until the game stops, or, in this case, until the bool is changed to false.

But what if you want a GameObject to rotate to a specific point and then stop? There are many ways to do this, but for this example, we will use a Coroutine. Coroutines are functions that carry out code over time and can be stopped at a designated point. We'll use a Coroutine to create the rotation effect without Update:

private void Update()
    {   

		if (Input.GetKeyDown(KeyCode.B))
		        {        
		            StartCoroutine(RotateObject());
		        }      
		 
    }  

IEnumerator RotateObject()
{
        float moveSpeed = 50f;        
        Quaternion endingAngle = Quaternion.Euler(new Vector3(45, 45, 0));        

        while (Vector3.Distance(itemToRotate.transform.rotation.eulerAngles, endingAngle.eulerAngles) > 0.01f)    
        {
            itemToRotate.transform.rotation = Quaternion.RotateTowards(itemToRotate.transform.rotation, endingAngle, moveSpeed * Time.deltaTime);           
            yield return null;
        }        

        itemToRotate.transform.rotation = endingAngle;
}

We start it off by hitting the B key. This triggers the StartCoroutine code, with the RotateObject() Coroutine as its target. Coroutines always require 'StartCoroutine' before they will trigger, so don't forget this vital piece of code.

Once the IEnumerator is triggered, it sets two local variables into play. moveSpeed dictates the speed of rotation, while the Quaternion endingAngle determines the desired angles you want the GameObject to reach. (In most cases, you will set the values of endingAngle outside the Coroutine, but this example is getting complicated enough as it is, so we'll keep it simple.)

Next up is the while() statement. while() acts as a sort of local Update(), executing code contained within it continuously until the conditions for stopping have been met. In this case while() will execute until itemToRotate's Rotation values are 0.01f different than those of endingAngle, using Distance to continuously calculate the difference between these values. While executing itemToRotate's Rotation values will utilize Quaternion.RotateTowards, which gradually adjusts the x and y values until they are almost - but not quite exactly - what you want.

(yield return null; dictates how long while will wait before it executes the rotation change again. Leaving it at 'null' will give you a smooth, continuous turn.)

RotateTowards will never reach the exact values you want, so once the while() statement gets close enough it will break off. We then set itemToRotate's Rotation values to those of endingAngle, resulting in nice, clean values rather than a bunch of decimals. The change in values is so small that there is no perceptible movement on screen. There! Object rotated.

Again, there are many ways to achieve this same effect, and results will vary depending on the path you take. As a small substitution, you can try 'Quaternion.Lerp' or 'Quaternion.Slerp' instead of RotateTowards, resulting in more gradual rotations that slow down the closer they get to their endpoints.

This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.

Related Articles