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 property of the GameObject. The following examples illustrate some basic transform operations and API usage, such as:
transform- property.
position - property.
rotation - ,
Translate,Rotatemethods.LookAt
For a complete reference of every member of the class and usage examples, refer to the API reference.
TransformTransformCode 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 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 package, which supported Unity versions install by default.
com.unity.inputsystem - The Active Input Handling setting in Edit>>Player settings set to Input System Package (New) or Both.Project Settings
?
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.
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 values aren't angles, so use to create a rotation from angles in degrees.
QuaternionQuaternion.Eulervoid 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 , , methods. The section describes the main concepts for a work with transforms, such as , difference between and , how to use , .
TranslateRotateLookAtSpacetransform.forwardVector3.forwardTime.deltaTimeQuaternion.SlerpChange 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 to prevent the GameObject from jittering. Because you call the method in the 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 by , which is the time in seconds after the last frame. This causes the GameObject to move at units per second, at any frame rate.
Time.deltaTimeMovePlayerUpdatemoveSpeedTime.deltaTimemoveSpeedFor more information about the method, refer to Per-frame updates.
Updatevoid 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 usage you can refer to the following example. It also shows the usage of the . is the GameObject's forward direction (z-axis) in World space. It changes when the player rotates. In comparison, is always (0, 0, 1). It doesn't depend on the way the player faces. With the default , gives the same result as the following example.
Translatetransform.forwardtransform.forwardVector3.forwardSpace.SelfTranslate(Vector3.forward * dashDistance)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 as a parameter in the call. The parameter decides which axes uses:
SpaceRotateSpaceRotate- rotates the GameObject relative to its own rotation. It's the default value.
Space.Self - rotates the GameObject by the
Space.Worldvalue around the World axes.eulerRotation
To learn more about , refer to the API reference.
SpaceSpacevoid 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 . The rotation will appear to snap to face the target. The second parameter, , is a hint for the direction of the GameObject's up direction (y-axis).
trueworldUpvoid 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 . The difference to previous example is that the rotation will appear to smoothly transition to face the target while you hold the F key.
falsevoid 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 component values to avoid unexpected behavior. All the following cases have an API that replaces a covered on this page.
TransformTransform APIRigidbody component
Don't set on a GameObject that has a Rigidbody component. Use the or methods instead. Adding a Rigidbody component to an object will put its motion under the control of Unity's physics engine. Setting directly bypasses the physics simulation and can cause unexpected behavior, such as GameObjects that miss collisions with other GameObjects.
transform.positionRigidbody.MoveRigidbody.MovePositiontransform.positionvoid 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 on a GameObject that has a CharacterController component. A only moves when you call the 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.
transform.positionCharacterControllerMovevoid 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 component instead of a , so 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 API, as in the following example.
RectTransformTransformtransform.positionRectTransformRefer to RectTransform, to learn more about the API.
RectTransformvoid 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 components to position its UI. The 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 , , , and . To learn more about UI Toolkit, refer to UI Toolkit.
TransformUI DocumentpositiontranslaterotatescalePerformance 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:
- to set world position and rotation of transform.
SetPositionAndRotation - to set local position and rotation of transform.
SetLocalPositionAndRotation
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:
- TransformHandle API for transform operations for Burst-compiled code that runs on the main thread.
- TransformAccessArray for jobs.
Complete code
To use the following code example:
- Copy the script.
- Save the script as in the Assets/ folder.
PlayerController.cs - Select a GameObject to which you want to apply the script.
- Drag the script in the Inspector window.
- Assign a GameObject in the field.
target - 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 }}