Transforming objects using scripts in Unity

3D Game Design with Unity

🕑 This lesson will take about 25 minutes

In this lesson, you will learn 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.

Is YouTube blocked at school? Watch on Google Drive.

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.

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:

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

Next lesson: Mouse input in Unity