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 3 of 5 of this article. Click here to view the first page.

Creating and Shooting Projectiles

Before you can start launching anything, you'll need to create a GameObject for the hay. Start off by creating a new empty GameObject in the Hierarchy by right-clicking an empty space and selecting Create Empty. This will generate an empty GameObject named "GameObject" at the root of the Hierarchy.

With the empty GameObject still selected, change its name to Hay Bale in the Inspector and reset its Transform component by right-clicking the Transform component and selecting Reset.

Now, add a 3D model to Hay Bale by dragging in the Hay Bale model from RW/Models onto Hay Bale in the Hierarchy. With the Hay Bale model still selected, name it Hay Bale Model and reset its Tranform. You'll now notice the hay firmly planted into the ground in both the Scene and the Game view.

Next, select Hay Bale and add the following components by using the Add Component button:

  • Box Collider
  • Rigidbody
  • Rotate

Now that the hay has the necessary components to use physics and can rotate around as a way of animating, it's time to configure it.

The bale will be shot from the hay machine, flying straight forward without being affected by gravity. Later in this tutorial, once you've added the sheep, they will be used to stop the sheep from hurting themselves.

To start off, check the Is Trigger checkbox on the Box Collider so the bale won't be able to push any rigid bodies around. Next, check the Is Kinematic checkbox on its Rigidbody so the hay won't drop through the ground. Finally, set the Rotation Speed on Rotation to (X:300, Y:50, Z:0).

Save the scene and press the play button. You'll notice the hay is spinning around in place.

To make the hay move forward, you'll need to write another utility script. Create a new C# script in RW/Scripts, name it Move and open it in your code editor.

Add the following variables declarations to the top of the class, right above the Start method:

public Vector3 movementSpeed; //1
public Space space; //2

Here's what they're used for:

  1. The speed in meters per second the attached GameObject will move in on the X, Y and Z axes.
  2. The space the movement will take place in, either World or Self. The World space transforms a GameObject in Unity's world space, ignoring the rotation of the GameObject, while Self considers the rotation of the GameObject in its calculations.

Now, add the following to Update:

transform.Translate(movementSpeed * Time.deltaTime, space);

This is what actually moves the GameObject by using a translation, that's a geometric term that means to transform a point by a distance in a given direction. Basically, it means to move GameObjects in the context of Unity.

The Translate method takes two parameters: The first is the direction and speed, while the second is the space in which the movement happens. The movement is multiplied by Time.deltaTime to perform a smooth movement over an amount of time.

Save this script and return to the editor. Add a Move component to Hay Bale, set its Movement Speed to (X:0, Y:0, Z:20) and leave Space set to World.

Now, play the scene and you'll see the hay bale flying towards the bridges and off the screen, great!

Drag Hay Bale into the RW/Prefabs folder to make it into a prefab and delete the original from the Hierarchy. You'll now be able to reference this prefab to create more whenever you want.

To make the hay machine shoot out the bales, you'll need to do some scripting. Open the HayMachine script and add the following variable declarations right above Start:

public GameObject hayBalePrefab; // 1
public Transform haySpawnpoint; // 2
public float shootInterval; // 3
private float shootTimer; // 4

Here's a brief explanation of the variables:

  1. Reference to the Hay Bale prefab.
  2. The point from which the hay will to be shot.
  3. The smallest amount of time between shots. This prevents the player from being able to spam the shoot button and fill the screen with bales of hay.
  4. A timer that decreases steadily to keep track whether the machine can shoot or not.

Now, add the ShootHay method below UpdateMovement:

private void ShootHay()
    Instantiate(hayBalePrefab, haySpawnpoint.position, Quaternion.identity);

The Instantiate method creates an instance of a given prefab or GameObject and places it in the scene. It takes three parameters: a prefab or GameObject, a position and a rotation. In this case, the reference to the Hay Bale prefab is used to create an instance with its initial position set to the same as the haySpawnpoint Transform. Quaternion.identity is used for the rotation, this is the default rotation value and is similar to Vector3.Zero as it sets the rotation to (X:0, Y:0, Z:0).

To call the code above, you'll need some code to poll for input. Add the following method just above ShootHay:

private void UpdateShooting()
    shootTimer -= Time.deltaTime; // 1

    if (shootTimer <= 0 && Input.GetKey(KeyCode.Space)) // 2
        shootTimer = shootInterval; // 3
        ShootHay(); // 4

Here's what this block of code does:

  1. Subtract the time between the previous frame and the current one from shootTimer, this will decrease its value by 1 every second.
  2. If the value of shootTimer is equal to or less than 0 and the space bar is pressed in...
  3. Reset the shoot timer.
  4. Shoot a bale of hay!

Lastly, add this line to Update, right below UpdateMovement();:


This calls the method above every frame.

Now, save this script and return to the editor. Select Hay Machine in the Hierarchy, unfold it by clicking the arrow to its left and take a look at the Inspector.

The new public variables you just added have become fields that can be assigned. Drag Hay Bale from RW\Prefabs onto the Hay Bale Prefab slot, drag Hay Machine's child Hay Spawnpoint onto the Hay Spawnpoint slot and set Shoot Interval to 0.8.

Now, save the scene and click the play button. Move the hay machine around with the arrow keys and shoot some hay using the space bar!

Everything should be working like the GIF above.

You may have noticed the bales never get destroyed and keep flying off endlessly into nothingness.

To fix this, you'll make smart use of triggers, tags and a line or two of code.