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
Share

In the first part of this tutorial, you learned how to move GameObjects around, handle player input and how to use the physics system using scripting. Of course, there’s a lot more you can do with C# and Unity’s API! In the second and last part of this tutorial, you’ll learn how to:

  • Create lists and iterate them.
  • Update UI elements.
  • Use the Event System.
  • Make use of the Singleton pattern.
  • Pass data between scenes to customize a game.

This will finish up the game you’re creating along the way, Sheep Rescue, in which you have to save the panicking sheep from their demise. At the end of this tutorial, you’ll have a small, finished game that’s easy to expand upon.

Below is a playable web version of the final result. The sound level is a tad on the high side, so you you might want to lower your volume:

Before starting off, make sure you have the latest stable version of Unity installed on your machine.

Getting Started

Download the materials for the project using the Download Materials button at the top or bottom of this tutorial, unzip it somewhere and open the starter project inside Unity. You can also use the finished project from the previous part of this tutorial as your starting point.

Open the Game scene under RW/Scenes if it isn’t opened automatically.

In the first part, you made a sheep run towards the ledge that could be shot by bales of hay launched by the hay machine. The Sheep is safely stored in the RW/Prefabs folder ready to be used.

The next step in creating the game is spawning the sheep at regular intervals in a way that they run over the little wooden bridges and towards their doom. There are several ways this can be tackled, but a simple way of doing it is using a bunch of spawn points and a small script that will create and keep track of the sheep.

Lists and Keeping Track of GameObjects

Start by creating a new empty GameObject at the root of the Hierarchy. Name it Sheep Spawn Points and reset its Transform.

Next, create three more empty GameObjects as children of Sheep Spawn Points and name each of these Spawn Point.

Now set the position of each of the spawn points to the following:

  • (X:-16, Y:0, Z:60)
  • (X:0, Y:0, Z:60)
  • (X:16, Y:0, Z:60)

This places the points evenly spaced on the map, right out of the camera’s view. Here are some sphere meshes added for illustration purposes to make it more clear:

With the spawn points defined, you’re ready to create the script for managing the sheep. Create a new C# script in RW/Scripts, name it SheepSpawner and open it in a code editor. Add the following variable declarations above Start:

public bool canSpawn = true; // 1

public GameObject sheepPrefab; // 2
public List<Transform> sheepSpawnPositions = new List<Transform>(); // 3
public float timeBetweenSpawns; // 4

private List<GameObject> sheepList = new List<GameObject>(); // 5

Here’s what they’ll be used for:

  1. As long as this stays true, the script will keep spawning sheep.
  2. A reference to a the Sheep prefab.
  3. The positions from where the sheep will be spawned. You need to create the list with the new keyword as Unity won’t initialize it correctly otherwise, causing errors if you try to add anything to the list.
  4. The time in seconds between the spawning of sheep.
  5. A list of all the sheep alive in the scene.

Now, add the most important method of this script, SpawnSheep:

private void SpawnSheep()
{
    Vector3 randomPosition = sheepSpawnPositions[Random.Range(0, sheepSpawnPositions.Count)].position; // 1
    GameObject sheep = Instantiate(sheepPrefab, randomPosition, sheepPrefab.transform.rotation); // 2
    sheepList.Add(sheep); // 3
    sheep.GetComponent<Sheep>().SetSpawner(this); // 4
}

This method spawns a single sheep at a random position:

  1. Use Unity’s Random class to get the position of one of the spawn point transforms. Random.Range(min, max) returns a random integer between 0 and the amount of spawn points available (three in this case), so the returned value will be either 0, 1 or 2.
  2. Create a new sheep and add it to the scene at the random position chosen in the previous line. Save this sheep in a temporary sheep variable.
  3. Add a reference to the sheep that was just created to the list of sheep.
  4. This line won’t compile yet as SetSpawner hasn’t been implemented yet so ignore the error. It will add a reference to the sheep spawner for the sheep to report to.

Save the SheepSpawner script and open the Sheep script. You’ll need to prepare it to make use of the spawner.

Add the following variable declaration below the others:

private SheepSpawner sheepSpawner;

This saves a reference to the sheep spawner. Now, add this method to fill in this reference:

public void SetSpawner(SheepSpawner spawner)
{
    sheepSpawner = spawner;
}

This method gets a reference to a SheepSpawner and caches it for later use.

Save the Sheep script and switch back to the SheepSpawner script.

Add this coroutine below the SpawnSheep method:

private IEnumerator SpawnRoutine() // 1
{
    while (canSpawn) // 2
    {
        SpawnSheep(); // 3
        yield return new WaitForSeconds(timeBetweenSpawns); // 4
    }
}

Coroutines are powerful methods that can run over time. Up until now, every method you’ve created ran to completion in a single frame. Coroutines, on the other hand, can be run over multiple frames or seconds as they can pause and resume their execution.

In the case of the SpawnRoutine, it will spawn a sheep, pause for a bit and then spawn another sheep for as long as the spawner is allowed to create new sheep. Here’s a rundown:

  1. All coroutines must use the IEnumerator return type. This allows you to yield (pause and resume execution) at any point.
  2. While canSpawn is true
  3. Spawn a new sheep.
  4. Pause the execution of this coroutine for the amount of seconds specified in timeBetweenSpawns using a yield instruction, WaitUntilSeconds in this case.
Note: There are a lot more yield instructions that can be used! There’s WaitForEndOfFrame, WaitForFixedUpdate and WaitUntil for example that are each useful. Check out this page for an example on how to use WaitUntil and links to all yield instructions.

Now, starting a coroutine is a bit different from simply calling a method. Add the following line inside of Start:

StartCoroutine(SpawnRoutine());

This line starts the coroutine. Instead of calling the coroutine directly you need to use StartCoroutine and pass the coroutine you want to start as a parameter.

Next, you need a way to remove sheep from the spawner’s list of sheep references when needed. Those references are being cached in order to easily destroy all sheep when the game ends. Add this method below SpawnRoutine:

public void RemoveSheepFromList(GameObject sheep)
{
    sheepList.Remove(sheep);
}

This method accepts a sheep as a parameter and removes its entry from the sheep list.

Now, add the following method:

public void DestroyAllSheep()
{
    foreach (GameObject sheep in sheepList) // 1
    {
        Destroy(sheep); // 2
    }

    sheepList.Clear();
}

This method destroys all of the sheep in the scene. Here’s how it does that:

  1. Iterate over every sheep in the list and destroy the GameObject each entry is referencing to.
  2. Clear the list of sheep references.

Save this script, open up the Sheep script and add this line to the top of both Drop and HitByHay:

sheepSpawner.RemoveSheepFromList(gameObject);

This removes the sheep from the spawner’s list when it drops off the edge of the world or gets hit by hay.

Now, save the Sheep script and return to the editor.

Add a new empty GameObject to the Hierarchy, name it Sheep Spawner and add a Sheep Spawner component.

To configure the spawner, start by dragging a Sheep from the RW/Prefabs folder onto the Sheep Prefab slot on the Sheep Spawner.

Next, expand Sheep Spawn Points and drag the spawn points one-by-one to the Sheep Spawn Positions list.

With the spawn points assigned, set Time Between Spawns to 2 to finish the setup.

Save the scene, press the play button and you should see the sheep appearing and running towards the hay machine. Try calming them with hay before they fall to their doom!

Looking good! The core gameplay is now ready, but you can go a step further by adding some cool effects.