Chapter 6. Building Gameplay with Traps and Objectives

Now that the foundations of the gameplay are set up, we can start adding in game elements like traps and treasure. From that point, much of the rest of the game is simply level design.

Simple Traps

Most of this game is about when the player hits things—traps, the treasure, the exit, and so on. Because detecting when the player hits certain objects is so important, we’ll create a generic script that triggers a Unity Event when any object that’s tagged with “Player” collides with it. This event can then be set up in different ways for different objects: the traps can be configured to tell the Game Manager that the gnome has received damage, the treasure can be configured to tell the Game Manager that the gnome has collected treasure, and the exit can be configured to tell the Game Manager that the gnome has reached the exit.

Now, create a new C# script called SignalOnTouch.cs, and add the following code to it:

  using UnityEngine.Events;

  // Invokes a UnityEvent when the Player collides with this
  // object.
  [RequireComponent (typeof(Collider2D))]
  public class SignalOnTouch : MonoBehaviour {

    // The UnityEvent to run when we collide.
    // Attach methods to run in the editor.
    public UnityEvent onTouch;

    // If true, attempt to play an AudioSource when we collide.
    public bool playAudioOnTouch = true;

    // When we enter a trigger area, call SendSignal.
    void OnTriggerEnter2D(Collider2D collider) {
      SendSignal (collider.gameObject);
    }

    // ...

Get Mobile Game Development with Unity now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.