Create a rotating cube in Unity3D

Are you starting to work with Unity3D? Creating objects an animating them is like the Hello World of any 3D authoring software. After reading this tutorial you have created your first Unity3D application that spins a Cube in 3D space.

Spinning cube

Create a new project

I use Unity 2017.1.0p5 and Visual Studio 2017 for this tutorial.

New project

Create project

Here is what a new project looks like in Unity3D. Your screen probably looks different because Unity allows you to rearrange all windows. Find all window options under the Window menu item.

Window

Create cube

Create Cube

A cube has now been added to the scene and the inspector shows its properties. The window title shows an asterisk in the text to indicate our scene has not been saved yet. Saving the scene is optional for this tutorial but here is how it works:

Needs save

Save main scene

Add Rigid Body

A rigid body enables game objects like our cube to be controlled by Unity’s physics engine. By default, Unity will control the objects gravity, resistance, etcetera. It also allows you as a developer to program your own scripts to control the object. And that’s why we will add the rigid body because it allows us to access to the game object with GetComponent<Rigidbody>() in C#

Add physics

Add rigid body

Disable gravity

Add script

To make the cube go spinning, we need to add a C# script to the cube.

Add script

Rotate script

A script has now been added and attached to the Cube

open in VS

Here is how it looks like in Visual Studio:

New script

Let’s cleanup the code a little bit.

Your code should look like:

using UnityEngine;

public class Rotator : MonoBehaviour
{
    void Start()
    {
    }
}

Do you remember that we added the Rigid Body to our cube? Here is where we are going to use it. Change your code to:

using UnityEngine;

public class Rotator : MonoBehaviour
{
    void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
    }
}

Because we added the Rigid Body, we can now access it in C#. Once we have stored the Rigid Body in the variable rg, we can set its angularVelocity, which is a Vector3 where X, Y and Z are the radians per second our cube needs to rotate. To create random values for X, Y and Z, we create a random vector using the Random class from Unity. Random.insideUnitSphere returns a random point inside a sphere with Radius = 1.

Play

We now have a rotating cube in Unity!

Spinning cube