Unity Tutorial - 3D Spinning Cube in 10 minutes

Edit a script

Let's make the cube spin now.

  • Double click on the SpinCube script in the Project window. This will automatically start Visual Studio. Doing that for the first time might take sometime.

    the project window in Unity with the script highlighted

  • Visual Studio should look something like this, once it's fully loaded:

    The visual studio editor window, showing some auto-generated code

    You should see two methods on the generated C# code:

    • Start(): a method that runs once when the cube gets created in a 3D scene.
    • Update(): a method that runs once for every frame of the object that the 3D engine draws to the screen. This means it runs every time the engine wants to figure out where the cube should be in the scene.
  • Visual Studio should look something like this, once it's fully loaded:

    The Visual Studio for Mac editor window, showing some auto-generated code

    You should see two methods on the generated C# code:

    • Start(): a method that runs once when the cube gets created in a 3D scene.
    • Update(): a method that runs once for every frame of the object that the 3D engine draws to the screen. This means it runs every time the engine wants to figure out where the cube should be in the scene.

Let's start writing a script to rotate the cube by creating a variable that will control the rotation.

  • Insert the highlighted line of code above the Start method. This code creates a public Vector 3, with x,y,z coordinates that will control the rotations in a 3D space.

    C#
    public Vector3 RotateAmount;
    // Start is called before the first frame update
    void Start()
    {
  • Then add the highlighted line of code inside the Update method. Every game object in Unity has a Transform script that dictates where it exists in 3D space and its rotation in 3D space. You'll use the Rotate method here and specify the rotation amount you want to happen on that game object.

    C#
    // Update is called once per frame
    void Update()
    {
    	transform.Rotate(RotateAmount);
    }
  • Press CTRL + S to save your changes in Visual Studio.
  • Press CMD + S to save your changes in Visual Studio.
  • Now, go back to the Unity editor and choose the Cube object in the Hierarchy window again.

  • On the Inspector window, you should find that the Public variable you've created is now visible under the new script you added to the cube.

    The spinning cube component showing x,y,z editable values in the Unity Inspector window

  • Change the Y value to 1, and then press the Play button on the top of the Unity editor.

    The play button in the Unity editor

    Since the Update method runs every frame, you'll see that the cube will rotate by one for every frame. Feel free to change those values up and have some fun. You're now ready to build the game for different platforms.

Continue