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.
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).
- Select the Spikes object in the scene view.
- Add a flow machine component
- Create a new macro for it named Spikes
- Apply the changes to the prefab
- 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:
- We listen for a collisions on the Spikes object
- When a collision happens, we check if the object owning the collider is tagged Player
- If it does, we send that object the Death event
- In the player object, we listen for the Death event
- 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:
The first thing we'll do is create a character controller.
In this part, we'll add level switching when we reach the red flag at the end of a level.