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
Share
You are currently viewing page 4 of 5 of this article. Click here to view the first page.

Tags and Reacting to Physics

To identify types of GameObjects, you can use tags. Tags are reference words like "Player" or "Collectible" you can assign to GameObjects to easily find them and differentiate them from other GameObjects. You can use any word or short sentence as a tag.

Creating a new tag is pretty easy, select Edit ► Project Settings... in the top menu and open the Tags and Layers tab in the Project Settings window. Now expand the Tags list and you'll notice the project already comes with two tags pre-loaded: DestroyHay and DropSheep.

Click the + button below the Tags list, name the new tag Hay and click the Save button to add this new tag to the list.

With the Hay tag added, close the Project Settings window and select Hay Bale in the RW\Prefabs folder. Open the Tag dropdown right below the name field and select Hay.

Now the difference between the bales of hay and other GameObjects is clear, you can add an area that destroys the hay when it comes into contact with it. Add a new empty GameObject to the Hierarchy and name it Triggers. Reset its Transform and add an empty GameObject as its child. Name this child Hay Destroyer.

Select Hay Destroyer, set its position to (X:0, Y:4, Z:68) and add a Box Collider to it. Check the Is Trigger checkbox on the Box Collider and set its Size to (X:60, Y:8, Z:12). Next, change the tag of Hay Destroyer to DestroyHay. You should now see a huge box-shaped collider appear in the Scene view, right outside of the camera's view.

Now, in order for this trigger to destroy any hay, you'll need to write yet another utility script. Create a new C# script inside RW\Scripts, name it DestroyOnTrigger and open it in a code editor. Remove the Start and Update methods completely and add this variable declaration in their place:

public string tagFilter;

This string will allow you to enter the name of any tag that will destroy this GameObject.

Now, add this method below the variable you just added:

private void OnTriggerEnter(Collider other) // 1
{
    if (other.CompareTag(tagFilter)) // 2
    {
        Destroy(gameObject); // 3
    }
}

Here's what's going on:

  1. OnTriggerEnter is a MonoBehaviour function, it's one of the special methods the Unity engine calls in specific circumstances. In this case, OnTriggerEnter gets called when a GameObject with a Rigidbody and a Collider enters the trigger area of a GameObject.
  2. Check if the GameObject that enters the trigger has the tag defined in tagFilter.
  3. Destroy the GameObject this script is attached to.

Save this script and return to the editor. Time to test it out!

Select Hay Bale in RW\Prefabs, add a Destroy On Trigger component and change Tag Filter to DestroyHay.

Now press the play button and try shooting some hay again. You'll notice any hay that hits the Hay Destroyer instantly gets obliterated.

Now that you have full control over the hay machine and its projectiles, it's time to introduce some fluffy friends.

Sheep Scripting

In the game you're creating, a bunch of sheep are panicking and running towards you, stopping at nothing. Unfortunately for them, that includes the ledge just behind the machine, yikes!

To start off, create a new empty GameObject in the Hierarchy and name it Sheep. Reset its Transform, set its Y rotation to 180 and add both a Box Collider and a Rigidbody. Check the Is Trigger checkbox of the Box Collider and change its Center and Size to (X:0, Y:1.4, Z:-0.3) and (X:2.5, Y:2, Z:4), respectively. Finally, check the Is Kinematic checkbox on the Rigidbody.

The Sheep should now look like this in the Inspector:

Now, drag the Sheep model from RW\Models onto Sheep to give it some visuals. Name the GameObject you just added Sheep Model, reset its Transform and set its X rotation to -90 so its head comes out of the ground.

This sheep is now ready to be scripted!

Note: Up until now, you have created generic scripts that can be reused for any GameObject, or even other projects. The script you're about to write is a lot more specific because its interactions are quite unique and will get more complicated over time as you add more features to the game.

Create a new C# script named Sheep in RW\Scripts and open it in a code editor.

To get started, the sheep simply needs to run forward and disappear when it gets hit by a hay bale. Add the following variable declarations right above Start:

public float runSpeed; // 1
public float gotHayDestroyDelay; // 2
private bool hitByHay; // 3

Here's what these are for:

  1. The speed in meter per second that the sheep will run.
  2. The delay in seconds before the sheep gets destroyed after it got hit by hay.
  3. A Boolean that gets set to true once the sheep was hit by hay.

With that out of the way, add this line to Update:

transform.Translate(Vector3.forward * runSpeed * Time.deltaTime);

This makes the sheep run towards its forward vector (the local Z axis) at the speed set in the runSpeed variable.

Next, add this method below Update:

private void HitByHay()
{
    hitByHay = true; // 1
    runSpeed = 0; // 2

    Destroy(gameObject, gotHayDestroyDelay); // 3
}

Here's the gist of this method:

  1. Set hitByHay to true, this will be useful to check if the method was already called, so it doesn't get called twice or more.
  2. Set the running speed to 0, this stops the sheep in its tracks.
  3. You've already seen this method call, but there's an extra parameter this time. The Destroy method accepts a second parameter, the delay in seconds before the GameObject gets destroyed. In this case, the delay variable you added above is used.

The last part is making the sheep react to physics by adding the following code:

private void OnTriggerEnter(Collider other) // 1
{
    if (other.CompareTag("Hay") && !hitByHay) // 2
    {
        Destroy(other.gameObject); // 3
        HitByHay(); // 4
    }
}

Here's what this does:

  1. This method gets called when a trigger enters this GameObject (or vice versa).
  2. If the GameObject that hit this one has the Hay tag assigned and the sheep wasn't hit by hay already...
  3. Destroy the other GameObject (the hay bale).
  4. Call the HitByHay method you added before this one.

That's it for now, save the script and return to the editor. Select Sheep in the Hierarchy and add a Sheep component. Set its Run Speed to 10 and Got Hay Destroy Delay to 1.

Now, play the scene, shoot the sheep and see what happens!

Awesome! The sheep stops moving and disappears like you've scripted it to. What happens if the sheep runs through without you shooting it though? Restart the scene and test that out.

The sheep flies over the edge as if by magic, that's no good! You'll have to create another trigger zone so the Sheep script can detect collisions with it and react accordingly.

Create a new empty GameObject as a child of Triggers, name it Sheep Dropper and reset its Transform. Set its position to (X:0, Y:4, Z:-54) and add a Box Collider with Is Trigger checked and a Size of (X:60, Y:8, Z:12). Now change its Tag to DropSheep and you'll have a nice big trigger behind the hay machine ready to be used.

When the sheep hits this trigger, it should fall down and get destroyed once out of sight. To implement this, you'll need to make some adjustments to the Sheep script. Open it again in a code editor and add the following variable declarations below the existing ones:

public float dropDestroyDelay; // 1
private Collider myCollider; // 2
private Rigidbody myRigidbody; // 3

They speak for themselves, but here's a brief overview:

  1. The time in seconds before the sheep gets destroyed when it's over the edge and starts dropping.
  2. Reference to the sheep's Collider component.
  3. A reference to the sheep's Rigidbody.

Now, assign the needed references by adding this to Start:

myCollider = GetComponent<Collider>();
myRigidbody = GetComponent<Rigidbody>();

This finds and caches the sheep's collider and rigidbody for later use.

Next, the sheep's collider setup needs adjustments so it gets affected by gravity. Add this method to do just that:

private void Drop()
{
    myRigidbody.isKinematic = false; // 1
    myCollider.isTrigger = false; // 2
    Destroy(gameObject, dropDestroyDelay); // 3
}

This method is simple:

  1. Make the sheep's rigidbody non-kinematic so it gets affected by gravity.
  2. Disable the trigger so the sheep becomes a solid object.
  3. Destroy the sheep after the delay specified in dropDestroyDelay.

Now, add the following to OnTriggerEnter, right below the existing if-statement:

else if (other.CompareTag("DropSheep"))
{
    Drop();
}

If the sheep was hit by something other than a hay bale, it checks if the collider it hit has the DropSheep tag assigned; Drop gets called if that's the case.

Now save this script and return to the editor. Select Sheep and change Drop Destroy Delay to 4.

Play the scene again and let the sheep move past the machine to see what happens.

Great! The sheep now falls down to its demise when the player fails to save it. Now that's motivating!

Now that the sheep acts as intended, drag it from the Hierarchy to the RW\Prefabs folder to turn it into a prefab and delete the original from the Hierarchy.

That's it for the first part of this tutorial! Pat yourself on the back, you have learned the basics of how to create scripts to implement gameplay in Unity.