Menu
CoddyTech

Turn Every Second

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 4 of 67.

transform.Rotate(x, y, z) turns a GameObject by that many degrees around each of its axes. Called in Update(), it turns a little on every frame, so the object keeps turning.

But how many frames is a second? On a fast computer maybe 120, on a phone maybe 30. A plain transform.Rotate(0, 0, 5) would spin four times faster on the fast one. Unity's answer is Time.deltaTime: the seconds that passed since the last frame. Multiply a speed by it and the speed means per second, on every device.

Here a wheel turns around its z axis, 45 degrees every second:

public float speed = 45f;

void Update()
{
    transform.Rotate(0, 0, speed * Time.deltaTime);
}

At 60 frames a second, Time.deltaTime is about 0.0167, so each frame turns 45 * 0.0167, about 0.75 degrees, and 60 of those make 45. At 30 frames a second each frame turns twice as far, and a second still adds up to 45.

challenge icon

Challenge

Easy

The cube has a Spinner script with a speed of 90. In Update(), make the cube turn around its y axis, speed degrees every second, on any device.

Press Play to watch it, then Check.

Try it yourself

using UnityEngine;

public class Spinner : MonoBehaviour
{
    public float speed = 90f;

    void Update()
    {
        // Turn the cube around its y axis here
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics