Transforming objects using scripts

This video tutorial will show you how to transform objects (move, rotate, scale) in your Unity game using C# scripts and also how to implement player interaction with the game by allowing players to transform objects using keypresses on their keyboard.

Watch the video below and then scroll down to see the sample code.

Here is some sample code with different object transformations assigned to different keypresses on the keyboard. You can change the transformations and assigned keys although it is a good idea to use the input manager rather than specific keypress detection so that your players have the option of remapping keys to suit their own preferences.

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 if (Input.GetKey (KeyCode.W)) {
 transform.Translate (0f,0f,0.1f);
 }
 if (Input.GetKey (KeyCode.S)) {
 transform.Translate (0f,0f,-0.1f);
 }
 
 if (Input.GetKey (KeyCode.D)) {
 transform.Translate (0.1f,0f,0f);
 }
 if (Input.GetKey (KeyCode.A)) {
 transform.Translate (-0.1f,0f,0f);
 }
 
 if (Input.GetKey (KeyCode.Z)) {
 transform.Rotate (0f,1f,0f);
 }
 
 if (Input.GetKey (KeyCode.X)) {
 transform.Rotate (0f,-1f,0f);
 }
 
 if (Input.GetKey (KeyCode.C)) {
 transform.localScale = new Vector3(1f,1f,1f);
 }
 
 if (Input.GetKey (KeyCode.V)) {
 transform.localScale = new Vector3(5f,5f,5f);
 }
 
 }
}

Note: If you find that the values for x, y and z axes seem to work the opposite to what you expect, it might be because you have the camera at a different angle. For example, if your camera is on the opposite side of your object, then pressing the key that is meant to move the object left might actually move it to the right.

Now try using variables to store the values for speed, eg:

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 public float turnSpeed = 5.0f;
 public float forwardSpeed = 0.25f;
 
 // Update is called once per frame
 void Update () {
 transform.Rotate(turnSpeed, 0.0f, 0.0f);
 transform.Translate(0.0f, 0.0f, forwardSpeed);
 }
}

Here is another method of moving objects on their own at a steady speed (this example does not include keyboard input).

using UnityEngine;
using System.Collections;
 
public class moveCube : MonoBehaviour {
 
 public float speed = 1.0f;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 transform.Translate (Vector3.forward * speed * Time.deltaTime);
 // This will move the cube forward on its own at steady speed
 // Vector3 is for 3D , Vector2 is for 2D
 // You can change Vector3.forward to Vector3.back, Vector3.left, or Vector3.right
 
 
 }
}