3. Spikes & Death

Updated: 2018-08-31

In this part, we will add a death mechanic when the player touches the spikes at the bottom of the level. We'll keep it very simple: as soon as you touch the spikes, the level gets reloaded.

1. Adding a death event

In your player controller graph, add a Death group with the following units:

  • Custom Event is located under Events
  • Get Active Scene and Load Scene are located under Codebase > Unity Engine > Scene Management > Scene Manager
  • Get Name is located under Codebase > Unity Engine > Scene Management > Scene

(Remember you can always search for the node name instead of browsing the fuzzy finder!)

Custom events allow us to listen to an event with any name we choose - in this case, we set it to Death. Later, when creating our spikes graph, we will trigger that event. Custom events also support any number of arguments, but in this case we don't need any (we'll use them later when creating health points and damage).

2. Triggering death on spike collision

  1. Select the Spikes object in the scene view.
  2. Add a flow machine component
  3. Create a new macro for it named Spikes
  4. Apply the changes to the prefab
  5. Delete the default Start and Update units

In that new graph, add these units:

  • On Collision Enter 2D is located under Events
  • Compare Tag is located under Codebase > Unity Engine > Game Object
  • Trigger Custom Event is located under Events

Let's recap what's happening here:

  1. We listen for a collisions on the Spikes object
  2. When a collision happens, we check if the object owning the collider is tagged Player
  3. If it does, we send that object the Death event
  4. In the player object, we listen for the Death event
  5. When we receive it, we reload the current scene

If you test your game now and fall on the spikes, you'll see that the level restarts:

Was this article helpful?
This article was helpful for 4 people.
Yes, helpful
No, not for me