---
title: Change a transform from a script
product: Unity Editor
version: '7000.0'
latest_version: '7000.0'
status: This page documents version 7000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/en-us/engine/7000.0/manual/working-with-gameobjects/transforms/modify-transforms-code
latest_url: https://docs.unity.com/en-us/engine/7000.0/manual/working-with-gameobjects/transforms/modify-transforms-code.md
last_updated: 2026-11-25
generated_at: 2026-11-27T22:48:39.220Z
locale: en-us
---

# 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.

You can manipulate transforms from a script by using the [`transform`](/engine/7000.0/script-reference/unityengine/gameobject/transform.md) 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`](/engine/7000.0/script-reference/unityengine/transform.md) 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](#complete-code) section. The code example uses the following mapping:

| **Key**                      | **Action**                  |
| ---------------------------- | --------------------------- |
| Press **W** and **S**        | Move forward and backward.  |
| Press **A** and **D**        | Move left and right.        |
| Press **Q** and **E**        | Turn left and right.        |
| Press **Space** and **Ctrl** | Fly up and down.            |
| Press **Shift**              | Dash forward.               |
| Press **X**                  | Turn around.                |
| Hold **F**                   | Face 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**>Editor>**Player** settings set to **Input System Package (New)** or **Both**.

To learn more about the Input System package, refer to [Input System](https://docs.unity3d.com/Packages/com.unity.inputsystem@latest/).

## 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`.

```cs
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.

```cs
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`](/engine/7000.0/script-reference/unityengine/transform/translate.md), [`Rotate`](/engine/7000.0/script-reference/unityengine/transform/rotate.md), [`LookAt`](/engine/7000.0/script-reference/unityengine/transform/lookat.md) 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`](/engine/7000.0/script-reference/unityengine/time/deltatime.md), [`Quaternion.Slerp`](/engine/7000.0/script-reference/unityengine/quaternion/slerp.md).

### 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](#complete-code), 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](/engine/7000.0/manual/scripting/managing-time-and-frame-rate/time-per-frame-updates.md).

```cs
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`](/engine/7000.0/script-reference/unityengine/transform/forward.md). `transform.forward` is the GameObject's forward direction (z-axis) in World space. It changes when the player rotates. In comparison, [`Vector3.forward`](/engine/7000.0/script-reference/unityengine/vector3/forward.md) 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.

```cs
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`](/engine/7000.0/script-reference/unityengine/space.md) as a parameter in the `Rotate` call. The `Space` parameter decides which axes `Rotate` uses:

* [`Space.Self`](/engine/7000.0/script-reference/unityengine/space/self.md) rotates the GameObject relative to its own rotation. It's the default value.
* [`Space.World`](/engine/7000.0/script-reference/unityengine/space/world.md) rotates the GameObject by the `eulerRotation` value around the World axes.

To learn more about `Space`, refer to [the `Space` API reference](/engine/7000.0/script-reference/unityengine/space.md).

```cs
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 ##look-at-code

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).

```cs
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**](#look-at-code) 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.

```cs
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`](/engine/7000.0/script-reference/unityengine/transform/position.md) on a GameObject that has a [Rigidbody](/engine/7000.0/manual/physics-section/physics-overview/rigidbody/class-rigidbody.md) component. Use the [`Rigidbody.Move`](/engine/7000.0/script-reference/unityengine/rigidbody/move.md) or [`Rigidbody.MovePosition`](/engine/7000.0/script-reference/unityengine/rigidbody/moveposition.md) 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.

```cs
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`](/engine/7000.0/script-reference/unityengine/transform/position.md) on a GameObject that has a [CharacterController](/engine/7000.0/manual/physics-section/physics-overview/character-control-section/class-character-controller.md) 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.

```cs
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](https://docs.unity3d.com/Packages/com.unity.ugui@latest/) 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](/engine/7000.0/script-reference/unityengine/recttransform.md), to learn more about the `RectTransform` API.

```cs
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](https://docs.unity3d.com/Packages/com.unity.ugui@latest?subfolder=/manual/UIAutoLayout.html#layout-element-component) 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.

```cs
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](/engine/7000.0/manual/uitoolkits/uielements.md) doesn't use GameObjects or `Transform` components to position its UI. The `UI Document` component only connects a [Unity Extensible Markup Language UXML](/engine/7000.0/manual/uitoolkits/uielements/uie-structure-ui/uie-uxml.md) 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)](/engine/7000.0/manual/uitoolkits/uielements/uie-uss.md) properties such as `position`, `translate`, `rotate`, and `scale`. To learn more about UI Toolkit, refer to [UI Toolkit](/engine/7000.0/manual/uitoolkits/uielements.md).

## 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:

* [`SetPositionAndRotation`](/engine/7000.0/script-reference/unityengine/transform/setpositionandrotation.md) to set world position and rotation of transform.
* [`SetLocalPositionAndRotation`](/engine/7000.0/script-reference/unityengine/transform/setlocalpositionandrotation.md) to set local position and rotation of transform.

### Leverage TransformHandle API with Burst

[Burst](/engine/7000.0/manual/scripting-compilation-burst.md) is a compiler, which translates from .NET [Intermediate Language (IL)](https://learn.microsoft.com/en-us/dotnet/standard/managed-code#intermediate-language--execution) to highly optimized native code using [LLVM](https://llvm.org/). This native code is optimized for performance on the target CPU architecture.

To modify a Transform component for Burst, use the following APIs:

* [TransformHandle API](/engine/7000.0/manual/working-with-gameobjects/transforms/transformhandle.md) for transform operations for Burst-compiled code that runs on the main thread.
* [TransformAccessArray](/engine/7000.0/script-reference/unityengine/jobs/transformaccessarray.md) for [jobs](/engine/7000.0/manual/scripting/programming-distribute-work-threads/job-system.md).

## Complete code ##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**.

```cs
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

* [GameObject fundamentals](/engine/7000.0/manual/working-with-gameobjects/gameobject-fundamentals.md)
* [Controlling rotation with the Quaternion class](/engine/7000.0/manual/scripting/programming-math/unity-engine-math/class-quaternion.md)
* [`Transform` API reference](/engine/7000.0/script-reference/unityengine/transform.md)
