Changing position
- Game Development course
- Beginner
- Lesson 38/83
- 4 min
Learn to change an object's place with transform.position.
Setting Position
transform.position represents an object's position in world space. You can move an object to another location by assigning a new Vector3 value to this property. Vector3 contains three numerical values representing the X, Y, and Z axes.
transform.position = new Vector3(2, 1, 4);This operation replaces the object's current position with the given coordinates.
Assigning Coordinates with Vector3
The Vector3 structure represents three-dimensional coordinates. In new Vector3(x, y, z), the first value is the X axis, the second is the Y axis, and the third is the Z axis. Assigning a value to Position places the object at the specified coordinates.
Vector3 targetPosition = new Vector3(4, 2, 6);
transform.position = targetPosition;Assigning a new value replaces the object's previous world position with the new coordinates.
Practice Place the Object at a New Position
Set the object's world position to (6, 2, 4) inside the Start method. Assign a new Vector3 to the transform.position property.
Starter code
using UnityEngine;
public class PositionSetter : MonoBehaviour
{
void Start()
{
// Assign the requested coordinates.
}
}Sample solution
using UnityEngine;
public class PositionSetter : MonoBehaviour
{
void Start()
{
transform.position = new Vector3(6, 2, 4);
}
}Expected output
(6.00, 2.00, 4.00)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement correctly places an object at world coordinates (5, 2, 3)?
- transform.position = new Vector2(5, 2);
- transform.position = new Vector3(5, 2, 3); Correct answer
- transform.scale = new Vector3(5, 2, 3);
- transform.rotation = new Vector3(5, 2, 3);
Explanation: A new three-axis Vector3 is assigned to the Position property. This sets the object's world position to (5, 2, 3).
2 Assign a New Position
transform.position = new Vector3(____);
transform.position = new Vector3(7, 3, 2);
Explanation: Vector3 values are provided in X, Y, and Z order. This places the object at coordinates (7, 3, 2).
3 Position and Vector3
| Term | Meaning |
|---|---|
transform.position |
Represents the object's world position |
Vector3 |
Stores a three-dimensional value |
X |
Is the first coordinate value |
Z |
Is the third coordinate value |