0
0
UnityHow-ToBeginner ยท 4 min read

How to Use transform.position in Unity: Simple Guide

In Unity, transform.position is used to get or set the position of a GameObject in world space. You can read it to find where the object is or assign a new Vector3 value to move it to a different spot.
๐Ÿ“

Syntax

The transform.position property holds the position of a GameObject in world coordinates as a Vector3. You can read it to get the current position or assign a new Vector3 to move the object.

  • transform: The Transform component of the GameObject.
  • position: A Vector3 representing the object's position in world space.
csharp
Vector3 currentPosition = transform.position; // Get current position
transform.position = new Vector3(1f, 2f, 3f); // Set new position
๐Ÿ’ป

Example

This example moves a GameObject to a new position (1, 2, 3) when the game starts and prints its position before and after moving.

csharp
using UnityEngine;

public class MoveObject : MonoBehaviour
{
    void Start()
    {
        // Print original position
        Debug.Log("Original position: " + transform.position);

        // Move object to new position
        transform.position = new Vector3(1f, 2f, 3f);

        // Print new position
        Debug.Log("New position: " + transform.position);
    }
}
Output
Original position: (x, y, z) New position: (1.0, 2.0, 3.0)
โš ๏ธ

Common Pitfalls

One common mistake is trying to modify transform.position directly on individual axes like transform.position.x = 5; which does not work because Vector3 is a struct and its fields are read-only in this context. Instead, create a new Vector3 with the desired values and assign it back.

csharp
/* Wrong way - does NOT change position */
// transform.position.x = 5f; // Error: Cannot modify

/* Right way - create new Vector3 and assign */
Vector3 pos = transform.position;
pos.x = 5f;
transform.position = pos;
๐Ÿ“Š

Quick Reference

  • Get position: Vector3 pos = transform.position;
  • Set position: transform.position = new Vector3(x, y, z);
  • Modify one axis: Create new Vector3 with changed axis and assign.
  • Position is in world space: Use transform.localPosition for local space.
โœ…

Key Takeaways

Use transform.position to get or set a GameObject's position in world space.
Always assign a new Vector3 to transform.position; you cannot change individual axes directly.
transform.position is in world coordinates; use transform.localPosition for local space.
Print transform.position to debug and verify object location.
Changing transform.position instantly moves the object in the scene.