Introduction to Unity Scripting – Part 1

Scripting is an essential part of making even the simplest of games. These small collections of code work together to do all sorts of things. By Eric Van de Kerckhove.

Leave a rating/review
Download materials
Save for later
You are currently viewing page 2 of 5 of this article. Click here to view the first page.


Variables are containers of data that store information. These can range from the player’s lives and money to a reference to a prefab to spawn into the scene. Once you add these to a script, you can edit their values in the editor.

Open the Rotate script in your favorite code editor and add the following line right above the Start method:

public Vector3 rotationSpeed;

This variable will change how fast and on what axis the rotation happens.

The public access modifier in the context of Unity means that this variable will be exposed to the editor and other classes.
A Vector3 is a struct that stores an X, Y and Z value, a Vector3 can be used to pass on the position, rotation or scale of a GameObject.

Now replace this line:

transform.Rotate(0, 50 * Time.deltaTime , 0);

With the following:

transform.Rotate(rotationSpeed * Time.deltaTime);

The rotation speed now gets fed into the Rotate method using a variable, making it easy to change. Vectors can be multiplied with single value variable types like deltaTime to change all included values of the vector at once. For example, a Vector3 with a value of (X:1, Y:2, Z:3) multiplied with a float with a value of 3 will result in a Vector3 with a value of (X:3, Y:6, Z:9).

Always opt for a variable instead of a “magic number” like the 50 you added in before. Doing so will allow you to change and reuse values without having to open the script.

Now, save the script and return to the editor. Open the Windmill prefab from the Hierarchy as you did before, and select the Wheel grandchild GameObject again.

Take a look at the Inspector, the Rotate component now has a field that you can adjust:

Change the Y value of the Rotation Speed field to 120 and exit the prefab mode by clicking the arrow at the top left of the Hierarchy, saving your changes when prompted.

Now, play the scene. The wheels are rotating like before, albeit a tad faster.

A huge advantage of having variables exposed in the editor is that you can change them while in play mode! Select the wheel of one of the windmills in the Hierarchy and try changing the Rotation Speed. You can slide the Y value from left to right or change the number directly.

Doing so will result in the wheel changing its speed in real time:

Once you stop play mode, any values you’ve set on GameObjects in the Hierarchy will be reset. This is a great way to play around with values and see what works best. You could tweak the height a character jumps, how much health the enemy orcs have or even the layout of UI elements.

Of course — once you have found the values you want — you might want to store these so they get applied each time the game starts. The most robust way to do this is by copying and pasting the values on components and using prefabs.

While still in play mode, change the rotation of one of the wheels to anything you think looks good, 150 on the Y-axis for example. Now right-click the Rotate component around its name in the Inspector, or left-click the options cog in the top right of the component, and select Copy Component. This will copy the component and its values to your clipboard.

Next, stop the play mode. You’ll notice the speed reverts to its former value in Inspector. Right-click the Rotate component’s name and select Paste Component Values, any values you’ve copied are now pasted into the Rotate component.

While this changed the rotation speed for one of the windmills, you want this applied to all of them. To do so, select the grandparent Windmill of the Wheel you’ve altered and select Overrides ► Apply All at the top right of Inspector to apply all changes to the Windmill prefab.

Next up is polling for player input to make the machine move and shoot!

Player Input and Instantiating Prefabs

A game wouldn’t be a game without requiring some level of player input. Scripts can get the state of the keyboard, mouse and any connected gamepads. The first goal is to get that little machine moving on the rails from left to right.


Create a new C# script in RW/Scripts, name it HayMachine and open it in a code editor.

Add the following variables right above Start:

public float movementSpeed;

This variable will allow you to specify the speed at which the machine can move.

Now, add this method below Update:

private void UpdateMovement()
    float horizontalInput = Input.GetAxisRaw("Horizontal"); // 1

    if (horizontalInput < 0) // 2
        transform.Translate(transform.right * -movementSpeed * Time.deltaTime);
    else if (horizontalInput > 0) // 3
        transform.Translate(transform.right * movementSpeed * Time.deltaTime);

This piece of code moves the hay machine around using the player’s horizontal input:

  1. Get the raw input of the Horizontal axis using the Input class and store it in horizontalInput. The Input class contains all the methods to poll input devices. GetAxisRaw returns the current value of input as defined in the input manager for the Horizontal axis:

In this case, you can use the left and right arrow keys, the A & D keys or a left analog stick as input.

  1. If horizontalInput is less than 0, that means a left movement on the X-axis was detected. In that case, translate (which means move) the machine to the left at a rate of its movementSpeed per second.
  2. If the horizontalInput is higher than 0 instead, move the machine to the right.

When Unity doesn’t detect any input, horizontalInput will stay at 0 and the machine won’t move.

Now, to call the method you’ve added each frame, add a call to it in Update:


Next, save this script and return to the editor. Select Hay Machine in the Hierarchy and add a Hay Machine component to it.

Set its Movement Speed to 14 and play the scene. Use the arrow keys or A & D to move the machine from left to right. It works!

Oops, you can move the machine outside of the rails and even off-screen, that’s no good. You’ll need to set up some boundaries to stop the machine from moving too far.

Open the HayMachine script again and add this variable below the others:

public float horizontalBoundary = 22;

This variable will be used to limit the movement on the X-axis. It gets assigned 22 as a default value, that will be the initial value that gets filled into the editor as well.

Now, edit UpdateMovement‘s if-else statement so it makes use of the boundary in its checks:

if (horizontalInput < 0 && transform.position.x > -horizontalBoundary) // 1
    transform.Translate(transform.right * -movementSpeed * Time.deltaTime);
else if (horizontalInput > 0 && transform.position.x < horizontalBoundary) // 2
    transform.Translate(transform.right * movementSpeed * Time.deltaTime);

Here's what changed:

  1. Not only does the horizontal input needs to be negative before allowing movement to the left, the machine's X position also needs to be higher than the negative value of horizontalBoundary.
  2. To move to the right, the horizontal input needs to be positive and the machine's X position should be lower than horizontalBoundary.

The image below illustrates what goes on more visually:

The white lines on the left and right represent the boundaries, the line going through the machine is its center. Moving the machine in either direction "locks" it once a boundary is reached:

Save the script and return to the editor. Try playing the scene and moving the machine left and right once more. The machine gets stopped once it's moved to one of the edges.
Next, you'll be implementing the shooting of bales of hay!