Menu
CoddyTech

Place the Cube

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 9 of 85.

Every GameObject has a Transform: its position, rotation and scale. A script reaches its own object's Transform as transform, and transform.position is where the object's center is, as a Vector3: three numbers for x (right), y (up) and z (forward, away from the camera). One unit is one meter.

To put an object somewhere, give it a new position in Start(). This lamp is 2 units tall and should stand on a table whose top is at y = 2, centered at x = -2, z = 4. The lamp's center goes half its height above the table top, so its y is 2 + 1 = 3:

void Start()
{
    transform.position = new Vector3(-2, 3, 4);
}

While the game plays, select the lamp in the Hierarchy: the Inspector's Transform shows the same three numbers as its Position.

challenge icon

Challenge

Easy

Rest the blue cube on the middle of the orange platform.

  1. In Start(), set transform.position to new Vector3(x, y, z).
  2. x and z are the platform's center: 3 and 2.
  3. y is the platform's top (1.5) plus half the cube's height: 1.5f + 0.5f.

Press Play: the cube sits on the platform. Then Check.

Try it yourself

using UnityEngine;

public class PlaceCube : MonoBehaviour
{
    void Start()
    {
        // x, y, z: change these three numbers
        transform.position = new Vector3(0f, 1f, 0f);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground