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
EasyRest the blue cube on the middle of the orange platform.
- In
Start(), settransform.positiontonew Vector3(x, y, z). - x and z are the platform's center:
3and2. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground