Trigger

Unity lesson #2: add triggers to call scripts

How could we use a script to stop ourselves from falling off the edge of the world?

Preparation

Before starting the trigger tutorial, complete the first-person character tutorial.

Follow the steps below to add a trigger onto your FPS game.

First, we need to think about our game design.

How do we know the player has fallen?

There are at least 2 logical ways to do it:

  • OPTION 1: Check the player’s height to see if their transform.position.y value is less than the height of the lava. This will be problematic if we need to go “below sea level” in future or have lava objects higher up.
  • OPTION 2: Make an actual cube to represent the lava below the ground and make it a trigger with a script that handles the OnTriggerEnter event when you touch it.

Let’s go with option 2. When the player has fallen, we need to decide what to do about it.

What should happen in the game when you fall off an edge?

We could do it at least 3 ways:

  • OPTION 1: In most games, you start over when you die or get stuck by returning to the start.
  • OPTION 2: In other games, you return to the most recent checkpoint.
  • OPTION 3: In Prince of Persia, you can rewind time to before you were in danger. The Chronos plugin lets you do that, but it is not beginner friendly.

Let’s go with option 1 and reload the current level if we fall.

Implement a lava cube that restarts the level

Create a lava cube to avoid falling infinitely

  1. Select the ground cube.
  2. Edit Menu / Duplicate it.
  3. Move the duplicate down.
  4. Rename the duplicate “lava“.
  5. Resize it to make it wider (100,1,100 scale) so it will catch you if you fall.
  6. Hit PLAY and try falling off the edge. Notice it catches you but you can walk further and fall off the edge still.
  7. Hit PLAY again to stop it.
  8. Click the “lava” cube to select it.
  9. In the Inspector, look for the Collider component.
  10. Check the “Is Trigger” checkbox.
  11. Hit PLAY and try falling off the edge. Notice it you now fall right through the lava cube without stopping.
  12. Hit PLAY again to stop the game.

Create your first script code to avoid falling infinitely

  1. In the Project pane, click Create / C# Script.
  2. Rename the script “Teleport“. Click it once to make the name changeable.
  3. Drag the Teleport script to the “lava” cube in the Scene, the Hierarchy or the bottom of its Inspector to attach it.
  4. Look in the inspector to confirm it is attached to the “lava” cube.

Edit the script to handle an OnTriggerEnter event:

  1. Double-click the “Teleport” C# script to edit it.
  2. Wait for MonoDevelop to load up.
  3. Double-click the “Teleport” C# script again if it is not already open to edit it.

How do we make triggers do something? Maybe documentation can tell us

  1. Click Help menu / Unity API Reference.
  2. Search for just “trigger”. We are going to find out how triggers work by searching the API Reference.
  3. Look at the results that come up for something that looks related to triggering an event when a collider is touched.
  4. Click  OnTriggerEnter (probably result 2).
  5. Select and copy the example code.
  6. Switch back to MonoDevelop.
  7. Paste the code in so it looks like this:
void OnTriggerEnter(Collider other)
{
    GameObject.Destroy(other);
}

Change the Destroy line to reload the current level instead.

Select and delete the GameObject.Destroy line.

void OnTriggerEnter(Collider other)
{ 

}
  1. Whatever we put between the { and } symbols will happen when something touches it.
  2. Click Help Menu / Unity API Reference to look for a way to make it do what we want.
  3. Type loadlevel into the search box and click Search.
  4. The first result is the one we want! Click Application.LoadLevel.
  5. Copy the example code into the space between our curly braces.
  6. Command-Tab or Alt-Tab to switch to MonoDevelop.
  7. Paste the example code on a blank line between the “function OnTriggerEnter {” and “}”.
  8. Your code should look like this:
void OnTriggerEnter( Collider other )
{
    Application.LoadLevel("Highscore");
}
  1. Change high score to “level1”:
void OnTriggerEnter( Collider other )
{
    Application.LoadLevel("level1");
}

Test

  1. Save your code.
  2. Switch to Unity.
  3. Save your scene and name the scene file “level1”.
  4. If you get an error about Build Settings, make sure to add it by going to File/Build Settings/Add Current.
  5. Hit PLAY to test it.
  6. When you jump off the edge and hit the lava, do you get teleported back to the top?
  7. If so, you are now a game developer, congratulations!

Expand your game level

  1. Make 10 cube platforms and position them with gaps so that you have to jump between the cubes.
  2. Arrange the cube gaps at increasing distances and difficulties until the last couple jumps are quite difficult but not impossible for you.
  3. Make sure that you always get teleported back to the start if you fall from anywhere in the level.

Make a portal that teleports between two levels

  1. Make a vertical wide narrow cube that looks like a door. (2.0, 3.0, 0.5 scale)
  2. Set it to IsTrigger true (checked).
  3. Attach Teleport to the door by dragging it onto the object or its name in the Hierarchy list part of the window.
  4. Double click Teleport.

Your code should look like this:

using UnityEngine;
using System.Collections;
public class Teleport : MonoBehaviour
{
    public bool restart = false;
    public string levelToLoad = "nameOfLevelToLoad";
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            if(restart)
            {
               Application.LoadLevel(Application.loadedLevel);
            }
                else
            {
                Application.LoadLevel( levelToLoad );
            }
        }
    }
}

Save the code. (Hit Command-S/Control-S keys or File Menu / Save )

Set the levelToLoad variable to go to level 2

  1. In Unity, click on the door object and look at the bottom of the inspector for the Teleport component.
  2. It will now have a text field labeled Level to load with the value in the box saying nameOfLevelToLoad.
  3. Click the box and type to change the text from nameOfLevelToLoad to say level2 instead.

Make a new scene called level2 so your portal has somewhere to go:

  1. File Menu / New Scene.
  2. File menu / Save the scene as “level2”.
  3. Repeat steps 1-9 to make yourself a new level with a new or duplicate “level1” as a starting template and rename the duplicate “level2”.
  4. Make sure the name of the second level matches the name referred to in the Teleport script.
  5. Add each of the levels in your game to the Build Settings list by clicking File Menu / Build Settings… and clicking Add Current after loading each one.
  6. Load the first level again.
  7. Play and walk into the first door.
  8. If it takes you to the first level again, congrats!
  9. Make the door glow white:
    1. In Project Panel, click Create / Material.
    2. Name it Unlit white.
    3. In the Inspector, click the color next to Emission and make it white instead of black.
    4. Drag the material onto the portal game object to assign it.

More Ways To Make Your First Level Fun

Now that you have a basic platforming game level that you can jump around in and try not to fall off the edge, it is time to make your level exciting and fun.

Make your lava red

  1. In Project panel, click Assets.
  2. Click Create and click Material.
  3. Type the name “LavaMaterial” and hit return.
  4. In the Inspector panel, there’s a white box to the right of Main Color. Click it.
  5. In the Color panel that pops up, pick a reddish color and close the Color panel.
  6. In Project panel, drag the LavaMaterial into the Hierarchy panel to drop it on the Lava object.
  7. You can even give it a tesxture!
  8. Use Google Image Search to search for “lava  texture”.
  9. Pick an image you like.
  10. Save it to your desktop.
  11. Drag it into your Unity project.
  12. On the lava material inspector, drag the lava texture into the Emission box.
  13. Set Albedo color to black.
  14. The lava should glow in the dark.
  15. Change tiling to something like 4 and 4 to avoid the lava texture looking stretched.

Expand your game level

  1. Make 10 cube platforms and position them with gaps so that you have to jump between the cubes.
  2. Arrange the cube gaps at increasing distances and difficulties until the last couple jumps are quite difficult but not impossible for you.
  3. Make sure that you always get teleported back to the start if you fall from anywhere in the level.

Your finished level should look something like this:

lava

Next tutorial: Pickup coins

Once you’ve made your first level have obstacles to avoid falling forever, it’s time to add some rewards for your players to seek.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s