O'Reilly logo

Mobile Game Development with Unity by Paris Buttfield-Addison, Jonathon Manning

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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);
    }

    // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required