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:
usingUnityEngine.Events;// Invokes a UnityEvent when the Player collides with this// object.[RequireComponent (typeof(Collider2D))]publicclassSignalOnTouch:MonoBehaviour{// The UnityEvent to run when we collide.// Attach methods to run in the editor.publicUnityEventonTouch;// If true, attempt to play an AudioSource when we collide.publicboolplayAudioOnTouch=true;// When we enter a trigger area, call SendSignal.voidOnTriggerEnter2D(Collider2Dcollider){SendSignal(collider.gameObject);}// ...