Documentation

Unity Engine

Download Unity

Unity Engine

Change a transform from a script

Code examples that demonstrate how to position and rotate GameObjects with transforms from scripts, and when to use other APIs instead.
Read time 14 minutesLast updated 2 days ago

You can manipulate transforms from a script by using the
transform
property of the GameObject. The following examples illustrate some basic transform operations and API usage, such as:
  • position
    property.
  • rotation
    property.
  • Translate
    ,
    Rotate
    ,
    LookAt
    methods.
For a complete reference of every member of the
Transform
class and usage examples, refer to the
Transform
API reference.

Code overview

The following code examples contain a basic GameObject controller that modifies GameObject transform values to navigate a GameObject in the scene. For the full code example, refer to the Complete code section. The code example uses the following mapping:

Key

Action

Press W and SMove forward and backward.
Press A and DMove left and right.
Press Q and ETurn left and right.
Press Space and CtrlFly up and down.
Press ShiftDash forward.
Press XTurn around.
Hold FFace the target GameObject.

Requirements

The following code example requires:
  • The
    com.unity.inputsystem
    package, which supported Unity versions install by default.
  • The Active Input Handling setting in Edit>
    Project Settings

    ?

    >Player settings set to Input System Package (New) or Both.
To learn more about the Input System package, refer to Input System.

Change transform positions

The following example illustrates some basic operations to move a GameObject along an y-axis with the Space and Ctrl keys.
Important
You can't directly assign the value to the axis. To assign the new value, you must use
Vector3
, because
transform.position
returns a
Vector3
copy of the current position. Direct assignment such as
transform.position.x = 5
causes the compiler error
CS1612
.
void MovePlayerVertically(Keyboard keyboard) { //Read the Space and Left Ctrl keys to decide whether to move up or down. float verticalInput = 0f; if (keyboard.spaceKey.isPressed) verticalInput += 1; if (keyboard.leftCtrlKey.isPressed) verticalInput -= 1; Vector3 playerPosition = transform.position; //Multiply by Time.deltaTime so the player moves at verticalSpeed units per second, at any frame rate. playerPosition.y += verticalInput * verticalSpeed * Time.deltaTime; //Apply the modified Vector3 value to the player transform position. transform.position = playerPosition; }

Change transform rotation

The following example illustrates some basic operations to rotate a GameObject with 180° around the y-axis when you press the X key. Make note, that
Quaternion
values aren't angles, so use
Quaternion.Euler
to create a rotation from angles in degrees.
void TurnAround() { //Access and assign a copy of the player local rotation value to Quaternion. Quaternion playerRotation = transform.localRotation; //Create a Quaternion that represents a rotation of 180 degrees around the y-axis. Quaternion rotationToAdd = Quaternion.Euler(0, 180, 0); //To combine rotations, you must multiply Quaternions. Adding them doesn't combine rotations. playerRotation *= rotationToAdd; //You can't directly assign the value to the axis. To assign the value, you must use Quaternion. //Assigning the value directly, such as transform.localRotation.y = 0, causes compiler error CS1612. transform.localRotation = playerRotation; }

Change transform with class methods

The following section illustrates how to use
Translate
,
Rotate
,
LookAt
methods. The section describes the main concepts for a work with transforms, such as
Space
, difference between
transform.forward
and
Vector3.forward
, how to use
Time.deltaTime
,
Quaternion.Slerp
.

Change transform with Translate

The following example illustrates some basic operations to move a GameObject on an x-axis and z-axis with the W, S, A, D keys.
Additionally, this example uses
Time.deltaTime
to prevent the GameObject from jittering. Because you call the
MovePlayer
method in the
Update
method
, which runs once per frame and frames don't consistently take the same amount of time, it can cause the GameObject to move inconsistently and appear to jitter. To correct this, multiply
moveSpeed
by
Time.deltaTime
, which is the time in seconds after the last frame. This causes the GameObject to move at
moveSpeed
units per second, at any frame rate.
For more information about the
Update
method, refer to Per-frame updates.
void MovePlayer(Keyboard keyboard) { //Read the WASD keys into a Vector3 that represents the move direction along the x and z axes. Vector3 moveInput = Vector3.zero; if (keyboard.wKey.isPressed) moveInput.z += 1; if (keyboard.sKey.isPressed) moveInput.z -= 1; if (keyboard.dKey.isPressed) moveInput.x += 1; if (keyboard.aKey.isPressed) moveInput.x -= 1; //Create a Vector3 that represents the distance to move the player this frame. Vector3 translation = moveInput * (moveSpeed * Time.deltaTime); //Move the player by the translation value along its own local axes. //Translate changes the transform directly, so you don't need to reassign the position like in other example. transform.Translate(translation, Space.Self); }
As another example of the
Translate
usage you can refer to the following example. It also shows the usage of the
transform.forward
.
transform.forward
is the GameObject's forward direction (z-axis) in World space. It changes when the player rotates. In comparison,
Vector3.forward
is always (0, 0, 1). It doesn't depend on the way the player faces. With the default
Space.Self
,
Translate(Vector3.forward * dashDistance)
gives the same result as the following example.
void Dash() { transform.Translate(transform.forward * dashDistance, Space.World); }

Change transform with Rotate

The following example illustrates some basic operations to rotate a GameObject with the Q and E keys.
Additionally, this example shows usage of the
Space
as a parameter in the
Rotate
call. The
Space
parameter decides which axes
Rotate
uses:
  • Space.Self
    rotates the GameObject relative to its own rotation. It's the default value.
  • Space.World
    rotates the GameObject by the
    eulerRotation
    value around the World axes.
To learn more about
Space
, refer to the
Space
API reference
.
void TurnPlayer(Keyboard keyboard) { //Read the Q and E keys to decide which way to turn. float turnInput = 0f; if (keyboard.eKey.isPressed) turnInput += 1; if (keyboard.qKey.isPressed) turnInput -= 1; //Create a Vector3 that represents a rotation of turnSpeed degrees per second around the y-axis. //Rotate uses Euler angles in degrees, so you don't need to create a Quaternion. Vector3 eulerRotation = new Vector3(0, turnInput * turnSpeed * Time.deltaTime, 0); //Rotate the player by the eulerRotation value around its own local axes. //Rotate adds to the current rotation instead of replacing it. transform.Rotate(eulerRotation, Space.Self); }

Change transform with LookAt

The following example rotates a GameObject so that its forward direction (z-axis) points at a target GameObject while you hold the F key and snap set to
true
. The rotation will appear to snap to face the target. The second parameter,
worldUp
, is a hint for the direction of the GameObject's up direction (y-axis).
void LookAtTargetSnap() { //Rotate the player so that its forward direction (z-axis) points at the target position. //LookAt replaces the current rotation, so it overrides the rotation applied in TurnPlayer. //Vector3.up is the default value of the second parameter. It keeps the player's up direction (y-axis) //as close to the World up as possible. transform.LookAt(target.transform, Vector3.up); }

Change transform with Slerp

The following example shows different approach to the Change transform with LookAt example. It rotates a GameObject so that its forward direction (z-axis) points at a target GameObject while you hold the F key and snap set to
false
. The difference to previous example is that the rotation will appear to smoothly transition to face the target while you hold the F key.
void LookAtTargetSmooth() { //Compute the rotation that makes the player's forward direction (z-axis) point at the target. Vector3 directionToTarget = target.transform.position - transform.position; if (directionToTarget == Vector3.zero) return; Quaternion targetRotation = Quaternion.LookRotation(directionToTarget, Vector3.up); //Spherically interpolate a fraction of the way from the current rotation toward the target rotation each frame, //so the player turns smoothly instead of snapping. //Multiply by Time.deltaTime to keep it frame-rate independent. transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, lookAtSpeed * Time.deltaTime); }

When not to modify the transform directly

When you work with transforms consider a few cases where to avoid directly modifying
Transform
component values to avoid unexpected behavior. All the following cases have an API that replaces a
Transform API
covered on this page.

Rigidbody component

Don't set
transform.position
on a GameObject that has a Rigidbody component. Use the
Rigidbody.Move
or
Rigidbody.MovePosition
methods instead. Adding a Rigidbody component to an object will put its motion under the control of Unity's physics engine. Setting
transform.position
directly bypasses the physics simulation and can cause unexpected behavior, such as GameObjects that miss collisions with other GameObjects.
void FixedUpdate() { //The physics simulation runs in FixedUpdate and writes the Rigidbody position and rotation to the Transform. //Use the Rigidbody methods instead of transform.position and transform.rotation so the move is part of the simulation. //Use Time.fixedDeltaTime because FixedUpdate runs at a fixed rate, not once per frame. Vector3 position = body.position + body.rotation * Vector3.forward * (moveSpeed * Time.fixedDeltaTime); Quaternion rotation = body.rotation * Quaternion.Euler(0, turnSpeed * Time.fixedDeltaTime, 0); body.Move(position, rotation); //You can use MovePosition and MoveRotation if you need to modify only one value. //The Move call is more efficient than calling methods for the position and the rotation separately. //body.MovePosition(position); //body.MoveRotation(rotation); }

CharacterController component

Don't set
transform.position
on a GameObject that has a CharacterController component. A
CharacterController
only moves when you call the
Move
method. By default, it detects collisions while it moves. If you modify GameObject's transform values directly, it might cause unexpected behavior with collision detection.
void FixedUpdate() { //CharacterController.Move checks for collisions while it moves the GameObject. //Setting transform.position directly skips the collision checks. //You could call CharacterController.Move in both Update and FixedUpdate methods. //Call it in FixedUpdate for better results in collision checks. characterController.Move(characterController.transform.forward * (moveSpeed * Time.deltaTime)); }

RectTransform component

UI elements created with uGUI have a
RectTransform
component instead of a
Transform
, so
transform.position
still works. However, the parent's anchors and layout components can override a position that you set this way. To position a UI element relative to its parent, use the
RectTransform
API, as in the following example.
Refer to RectTransform, to learn more about the
RectTransform
API.
void Start() { //uGUI elements have a RectTransform, a subclass of Transform that adds anchors, a pivot, and a size. //Anchor the panel to the top center of its parent, and set its pivot to its own top center. uiPanel.anchorMin = new Vector2(0.5f, 1); uiPanel.anchorMax = new Vector2(0.5f, 1); uiPanel.pivot = new Vector2(0.5f, 1); //Move and resize the panel with anchoredPosition and sizeDelta instead of position. //anchoredPosition is the pivot position relative to the anchors, so the layout adapts to different screen sizes. uiPanel.anchoredPosition = new Vector2(0, -20); uiPanel.sizeDelta = new Vector2(200, 50); }
Also, the Layout Element component lets you set the minimum, maximum, preferred, and flexible width and height of a UI element. A parent layout group uses these values to size and position the element.
void SetPreferredSize() { //A layout group or a content size fitter overwrites the position and size that a script sets. //If the parent has a layout group, set the preferred size with a LayoutElement, and the layout group uses it. layoutElement.preferredWidth = 200; layoutElement.preferredHeight = 50; }

UI Toolkit

UI Toolkit doesn't use GameObjects or
Transform
components to position its UI. The
UI Document
component only connects a Unity Extensible Markup Language UXML document to a panel. The panel renders the UI independently of the GameObject's position, rotation, and scale. To position, rotate, or scale UI elements, use Unity Style Sheet (USS) properties such as
position
,
translate
,
rotate
, and
scale
. To learn more about UI Toolkit, refer to UI Toolkit.

Performance considerations

Learn about methods, APIs, and approaches to optimize your work with transform operations.

Set the position and rotation in one call

When you need to set both the position and rotation of a transform, one method call is more efficient than assigning the position and the rotation separately. Use:

Leverage TransformHandle API with Burst

Burst is a compiler, which translates from .NET Intermediate Language (IL) to highly optimized native code using LLVM. This native code is optimized for performance on the target CPU architecture.
To modify a Transform component for Burst, use the following APIs:

Complete code

To use the following code example:
  1. Copy the script.
  2. Save the script as
    PlayerController.cs
    in the Assets/ folder.
  3. Select a GameObject to which you want to apply the script.
  4. Drag the script in the Inspector window.
  5. Assign a GameObject in the
    target
    field.
  6. Select Play.
using UnityEngine;using UnityEngine.InputSystem;namespace Docs.CoreProgramming{ public class PlayerController : MonoBehaviour { [SerializeField] float moveSpeed = 5f; [SerializeField] float turnSpeed = 90f; [SerializeField] float verticalSpeed = 3f; [SerializeField] float dashDistance = 2f; [SerializeField] float lookAtSpeed = 5f; [SerializeField] bool snap = false; [SerializeField] GameObject target; #region Update void Update() { Keyboard keyboard = Keyboard.current; if (keyboard == null) return; MovePlayer(keyboard); MovePlayerVertically(keyboard); TurnPlayer(keyboard); //Press Left Shift to dash forward. if (keyboard.leftShiftKey.wasPressedThisFrame) Dash(); //Press X to turn around. if (keyboard.xKey.wasPressedThisFrame) TurnAround(); //Hold F to face the target. if (keyboard.fKey.isPressed) LookAtTarget(snap); } #endregion #region ExamplePosition void MovePlayerVertically(Keyboard keyboard) { //Read the Space and Left Ctrl keys to decide whether to move up or down. float verticalInput = 0f; if (keyboard.spaceKey.isPressed) verticalInput += 1; if (keyboard.leftCtrlKey.isPressed) verticalInput -= 1; Vector3 playerPosition = transform.position; //Multiply by Time.deltaTime so the player moves at verticalSpeed units per second, at any frame rate. playerPosition.y += verticalInput * verticalSpeed * Time.deltaTime; //Apply the modified Vector3 value to the player transform position. transform.position = playerPosition; } #endregion #region ExampleQuaternion void TurnAround() { //Access and assign a copy of the player local rotation value to Quaternion. Quaternion playerRotation = transform.localRotation; //Create a Quaternion that represents a rotation of 180 degrees around the y-axis. Quaternion rotationToAdd = Quaternion.Euler(0, 180, 0); //To combine rotations, you must multiply Quaternions. Adding them doesn't combine rotations. playerRotation *= rotationToAdd; //You can't directly assign the value to the axis. To assign the value, you must use Quaternion. //Assigning the value directly, such as transform.localRotation.y = 0, causes compiler error CS1612. transform.localRotation = playerRotation; } #endregion #region LocalAndWorldSpace void MovePlayer(Keyboard keyboard) { //Read the WASD keys into a Vector3 that represents the move direction along the x and z axes. Vector3 moveInput = Vector3.zero; if (keyboard.wKey.isPressed) moveInput.z += 1; if (keyboard.sKey.isPressed) moveInput.z -= 1; if (keyboard.dKey.isPressed) moveInput.x += 1; if (keyboard.aKey.isPressed) moveInput.x -= 1; //Create a Vector3 that represents the distance to move the player this frame. Vector3 translation = moveInput * (moveSpeed * Time.deltaTime); //Move the player by the translation value along its own local axes. //Translate changes the transform directly, so you don't need to reassign the position like in other example. transform.Translate(translation, Space.Self); } #endregion #region ForwardDifferences void Dash() { transform.Translate(transform.forward * dashDistance, Space.World); } #endregion #region Rotate void TurnPlayer(Keyboard keyboard) { //Read the Q and E keys to decide which way to turn. float turnInput = 0f; if (keyboard.eKey.isPressed) turnInput += 1; if (keyboard.qKey.isPressed) turnInput -= 1; //Create a Vector3 that represents a rotation of turnSpeed degrees per second around the y-axis. //Rotate uses Euler angles in degrees, so you don't need to create a Quaternion. Vector3 eulerRotation = new Vector3(0, turnInput * turnSpeed * Time.deltaTime, 0); //Rotate the player by the eulerRotation value around its own local axes. //Rotate adds to the current rotation instead of replacing it. transform.Rotate(eulerRotation, Space.Self); } #endregion #region LookAt void LookAtTarget(bool snap) { if (snap) LookAtTargetSnap(); else LookAtTargetSmooth(); } #endregion #region LookAtSnap void LookAtTargetSnap() { //Rotate the player so that its forward direction (z-axis) points at the target position. //LookAt replaces the current rotation, so it overrides the rotation applied in TurnPlayer. //Vector3.up is the default value of the second parameter. It keeps the player's up direction (y-axis) //as close to the World up as possible. transform.LookAt(target.transform, Vector3.up); } #endregion #region LookAtSmooth void LookAtTargetSmooth() { //Compute the rotation that makes the player's forward direction (z-axis) point at the target. Vector3 directionToTarget = target.transform.position - transform.position; if (directionToTarget == Vector3.zero) return; Quaternion targetRotation = Quaternion.LookRotation(directionToTarget, Vector3.up); //Spherically interpolate a fraction of the way from the current rotation toward the target rotation each frame, //so the player turns smoothly instead of snapping. //Multiply by Time.deltaTime to keep it frame-rate independent. transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, lookAtSpeed * Time.deltaTime); } #endregion }}

Additional resources