character killed

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Themaker482
:warning: Old Version Published before Godot 3 was released.

I want to know a way to repeat a scene from the begining when my character get killed and dissapear, can someone give me some tips?

:bust_in_silhouette: Reply From: atze

There are probably better solutions but here is what I did:

When the player gets killed, switch to another scene (e.g. a game over screen),
if the player decides to play again, switch back to the previous scene.

Another approach would be to have function, that resets all variables, etc in the scene/subscenes to their initial states, but I couldn’t get this working 100%

:bust_in_silhouette: Reply From: kakoeimon

A simple way to do this is by calling:
get_tree().reload_current_scene()
If you want some vars to keep their values consider using a singleton

You should avoid accessing objects outside your scene, it’s bad for debugging, code reusability and readability. Instead add a signal that is emitted when the player dies and have the parent scene react to it. That way there’s no need to access the scene tree or use a singleton, both of which could be a problem if you later decide to make everything you have a child of a new menu scene or something.

Warlaan | 2016-05-29 10:06

Yes signals are a good way to go. But then again it may be easier some times to have access to an object outside your scene or use a singleton. Mostly it depends on the game design.
For example the player node can have a local score and pass the local score to the singleton when the player finishes the stage or automatically reset the local score when you reload the player.

kakoeimon | 2016-05-29 10:53

:bust_in_silhouette: Reply From: Zylann

You can also do it without singletons:
In my game, I have a “host” scene inside of which I instantiate the level under a known node. When I need to restart the level, I simply destroy the level, then re-instantiate it.
The reason for this technique is to prevent other parts of the scene to get wiped out (GUI elements, game variables, sound node, global animations…), so you don’t need to reload everything and you can keep some nodes between retries.

Another technique I use (but more complicated depending on your levels) is to consider that “destroyed” is just a state, so you never destroy and never create elements in the level. If you have a script to remember their initial state, then reloading the level just requires to go back to initial states with a group event. This is very fast because you allocate less memory and fewer nodes are recomputed. But you’ll want another technique if your level evolves too much.