Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Loss State | Programming with C# - Extra Mechanics
Unity for Beginners

bookLoss State

Svep för att visa menyn

Our level is now playable and the camera works correctly.

But there's a problem:

If the player falls out of view, the game keeps running. There is no loss state.

Creating a Loss Zone

To detect when the player loses:

  • create an Empty GameObject (e.g., LossZone);
  • add a Box Collider 2D;
  • tick Is Trigger.

Why use Is Trigger?

Because we don't want the player to physically collide and stop - we only want to detect when they enter the area.

Making It Follow the Camera

In an endless jumper, the player can reach great heights. If the loss zone stayed fixed at the bottom, the player might fall for a long time before triggering a restart.

Instead:

  • make the LossZone a child of the Camera;
  • position it just below view;
  • when the camera moves, the LossZone moves with it.

Now it always stays just below the visible area.

Detecting the Trigger

Because we enabled Is Trigger, we use:

OnTriggerEnter2D()

Instead of:

OnCollisionEnter2D()

Then we check that the object entering is the Player:

if (collision.gameObject.name == "Player")

(If "Player" is the name of the player GameObject in your scene!)

Reloading the Scene

To restart the level, we must use Unity's Scene Management system.

At the top of the script:

using UnityEngine.SceneManagement;

This allows access to scene functions.

Then to reload the current scene:

SceneManager.LoadScene(SceneManager.GetActiveScene().name);

This loads the scene that is currently active, effectively restarting the game.

1. Why did we enable "Is Trigger" on the LossZone collider?

2. Which function is used when a Collider2D is set as a trigger?

3. What does this line of code do?

question mark

Why did we enable "Is Trigger" on the LossZone collider?

Vänligen välj det korrekta svaret

question mark

Which function is used when a Collider2D is set as a trigger?

Vänligen välj det korrekta svaret

question mark

What does this line of code do?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 4. Kapitel 2
some-alt