Introduction to Unity Scripting – Part 2

In the second and last part of this tutorial, you will finish the game Sheep Rescue, in which you have to save the panicking sheep from their demise! By Eric Van de Kerckhove.

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

Passing Data Between Scenes

The ability to pass data between scenes can be useful for passing things like game settings from an options menu to the game. For this game, you'll implement the option to change the color of the hay machine from the title screen.

To start, you need something to click on to make the color change happen. Create an empty GameObject in the root of the Hierarchy, name it Hay Machines and set its position to (X:16.5, Y:-0.5, Z:-20). This will act as a container for the differently colored hay machines.

Now, select all of the hay machines in RW/Prefabs/Hay Machine Models and drag them to Hay Machines.

Next, with the three hay machines elected in the Hierarchy, set their Rotation to (X:-90, Y:0, Z:0). The hay machines are now upright:

Right now, all of the machines are overlapping so a random gets visibly rendered. The default machine color is blue, so disable the other two by clicking the little checkbox next to their names, or by pressing Alt + Shift + A.

To make the hay machines clickable, they need a collider. Add a Box Collider to Hay Machines, set its Center to (X:0, Y:3.5, Z:0) and its Size to (X:5, Y:6, Z:8).

You're now ready to do some scripting! Create a new folder in RW/Scripts, name it Shared and create a new C# script inside of it named HayMachineColor.

Open it in a code editor and strip out all of the using statements and both methods.

Now, replace this line:

public class HayMachineColor : MonoBehaviour

With this:

public enum HayMachineColor

As you might've guessed, this script isn't meant to be used as a component, it's actually just a simple enum that will be used by other scripts. Enums are actually just constant integers under the hood (like 0, 1, 2, etc.) but using them makes for a much more approachable and readable way of accessing variables. Add this inside of the body of the enum to add some values:

Blue, Yellow, Red

That's it for this file, save it, return to the editor and create another C# script inside RW/Scripts/Shared. Name it GameSettings and open it in your code editor. Strip the using statements and the methods again, this will be a a regular class.

Replace this line:

public class GameSettings : MonoBehaviour

With this one:

public static class GameSettings

This turns this script into a static class that can hold data for other scripts to use, even across scenes. Any static variables added to this class can be set from the title screen and then read by the game screen for example, which can be quite powerful!

Now, add this variable declaration to the body of the class:

public static HayMachineColor hayMachineColor = HayMachineColor.Blue;

This is where the magic happens! This variable will be used to set and get the color of the hay machine. It uses the enum you just created for readability.

Save this script, return to the editor and create yet another script in RW/Scripts/Shared named HayMachineSwitcher.

Open the script in a code editor and add these using statements below the others:

using UnityEngine.EventSystems;
using System;

This is needed to be able to use the pointer click event.

Replace this line:

public class HayMachineSwitcher : MonoBehaviour

With this one:

public class HayMachineSwitcher : MonoBehaviour, IPointerClickHandler

Like before, you'll get an error about missing an interface member, but don't worry about that!

Now, add these variable declarations:

// 1
public GameObject blueHayMachine;
public GameObject yellowHayMachine;
public GameObject redHayMachine;

private int selectedIndex; // 2
  1. These variables reference each of the colored hay machine models you added as children of Hay Machines earlier.
  2. This is an index that will be incremented whenever the hay machine selector is clicked, triggering the next machine color to be chosen. It will become clear what this entails exactly once you add the method next.

Now, remove the Start and Update method and add the most important method of this script:

public void OnPointerClick(PointerEventData eventData) // 1
    selectedIndex++; // 2
    selectedIndex %= Enum.GetValues(typeof(HayMachineColor)).Length; // 3

    GameSettings.hayMachineColor = (HayMachineColor)selectedIndex; // 4

    // 5
    switch (GameSettings.hayMachineColor)
        case HayMachineColor.Blue:

        case HayMachineColor.Yellow:

        case HayMachineColor.Red:

This is what the method does:

  1. This is the same method as you used with the title buttons; it gets called when this GameObject gets clicked and has a single parameter that contains a bunch of information about the pointer input.
  2. Increment selectedIndex so the next color gets selected.
  3. This line uses algebra to prevent writing unnecessary if-statements. Using the modulo (%) operator to get the remainder of the division, the index can be "looped around". The right part of this equation looks intimidating, but it simply gets a list of all values contained in the HayMachineColor enum and counts them. Its value, in this case, would be 3. Here's an example of how these work together: If the index is 3, the remainder after dividing it by the amount of colors (3) is 0. So, the final index value would be 0. On the other hand, if the index is 2 and it gets divided by the amount of colors (3), the remainder is 2. So, the value of the index stays 2. Here's a website where you can try playing with these values. The dividend is the current index value, the divisor is the amount of colors and the remainder is the final index value.
  4. Set the chosen color in GameSettings depending on the selected index, which is cast to an enum by adding the cast type in parenthesis before the variable.
  5. Enable and disable the hay machine models based on the chosen machine color using a switch-statement.

This was the most complicated block of code in this project by far, but, the end result will be pretty cool!

Save this script and return to the editor. Select Hay Machines, add a Hay Machine Switcher component and drag the hay machine children onto their matching slots.

Now, for the moment of truth! Play the scene and click a few times on the hay machine on the right. You'll see it switching colors!

If you start the game now, though, the hay machine will still be blue, no matter what other color you've chosen. The final piece of the puzzle is editing the hay machine script, so it'll take the chosen color value and apply it on startup.

Open the HayMachine script and add the following variable declarations below the others:

public Transform modelParent; // 1

// 2
public GameObject blueModelPrefab;
public GameObject yellowModelPrefab;
public GameObject redModelPrefab;

These will be used for swapping the machine model:

  1. The parent Transform of the model.
  2. References to the hay machine model prefabs.

Now, add the following method below Start:

private void LoadModel()
    Destroy(modelParent.GetChild(0).gameObject); // 1

    switch (GameSettings.hayMachineColor) // 2
        case HayMachineColor.Blue:
            Instantiate(blueModelPrefab, modelParent);

        case HayMachineColor.Yellow:
            Instantiate(yellowModelPrefab, modelParent);

        case HayMachineColor.Red:
            Instantiate(redModelPrefab, modelParent);

This replaces the default model with a new one depending on the machine color saved in the game settings:

  1. Destroy the current model.
  2. Instantiate a hay machine model prefab based on the chosen color and parent it to modelParent.

Finally, add this line to Start:


This calls the LoadModel method you just created.

Now, save the script and return to the editor. Make sure the Title scene is saved. Open the Game scene, select Hay Machine and expand it in the Hierarchy.

The Hay Machine component now has some extra fields that need to be filled in for the model switching to work. Drag Model Parent to the Model Parent slot and drag the prefabs found in RW/Prefabs/Hay Machine Models to their corresponding slots.

With the hay machine fully set up, save the Game scene. Open the Title scene again and press the Play button. Switch the color of the hay machine to something different than blue, and press the Start button.

You'll now see that the hay machine has the color you've chosen!

Congratulations! You have made a complete game from just a few models and implemented some cool mechanics while learning about Unity's API along the way.