Tutorial: Instant Death - CodingDino/Dino-Unity-Toolkit GitHub Wiki

In this tutorial, you will learn how to create hazards (or enemies) that kill the player instantly on touch. In this case, we'll use some spikes as an example. We'll accomplish the player "death" by reloading the current scene when the player touches the spikes.

This tutorial requires a moving player using something like the Tutorial: Platformer Player Movement. It also requires a spikes sprite with a 2D collider attached to it. Example assets are provided in the tutorial package.

Before we start, let's clearly state our goal behaviour:

Reset the player's progress to the beginning of the level whenever the player touches the spikes.

Action

In the stated goal behaviour above, the first part of the sentence describes the Action that should occur:

Reset the player's progress to the beginning of the level...

Our action is to reset the level. We accomplish this by using a SceneAction component. This component can be used to load other scenes, or to reload our current one.

Drag your spikes sprite into the scene. Now add the SceneAction component to the spikes.

The action is now all ready to use - but as always, it must be triggered by an Activator in order to actually happen.

Activator

In the stated goal behaviour above, the second part of the sentence describes the Activator condition:

...whenever the player touches the spikes.

So, we want an activator that will do something when the player touches a specific object. For this, we'll use the OnCollision2DActivator.

Attach a collider to your spikes (such as a BoxCollider2D). Now add the OnCollision2DActivator component.

You'll notice this activator has some condition fields. We'll use those to make sure that the scene is only reloaded when the player touches the spikes - we wouldn't want it resetting the level when an enemy touched them!

Check the "Check Tag" box and type "Player" into the "Target Tag" field that appears. This means that the Activator will only trigger if the thing that bumped into the spikes has the "Player" tag.

We should therefore add that tag to our player - otherwise the Activator will never trigger the Action. Select your player and click the "Tag" dropdown in the top left of the inspector.

Select the "Player" tag from the dropdown.

Now our conditions are all set up. All we need to do is add the actual connection between our Activator and our Action.

Click back on the spikes. Add a new action to the "On Collision Enter Actions" list. Drag the spikes GameObject into the GameObject slot for the action, then open the dropdown. Select SceneAction > ActionReloadCurrentScene.

Testing

If you did the above steps correctly, you should now be able to run your scene, move your player onto the spikes, and the scene should be reset to the starting point. Try it out!