How does one go about making a KinematicBody2D "Persistent" though scenes?

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

So when I was using GameMaker, GM have this “Persistent” option that basically makes your object(“Player”) persistent through scenes. It would retain the position and state of the object when it leaves the scene, and when it goes back.

My question is, does Godot have this function?
If not, how would you go about doing this?

:bust_in_silhouette: Reply From: Zylann

I see a few options for persistent nodes (not just a player):

  1. Use an auto-load singleton, which will make your node present in all scenes of your game (even the main menu though, if you have one). Documentation here: Singletons (Autoload) — Godot Engine (stable) documentation in English

Next solutions require a bit of scripting:

  1. Dynamically instance the player, remove it from the tree (remove_child) before changing scene (it won’t delete it), and add it back in the scene once it is loaded (add_child). That requires a bit of code in a singleton (like in 1) )and the setup of “spawn points” using Position2D for example, so that you know where to put the node.

  2. Don’t use change_scene, because as you noticed it replace everything by a new scene. But because Godot games are scene trees, an alternative is to have one scene that removes and loads the others under a child node. This way, the “container” can have common nodes that will be preserved because they are in a parent or another branch. I use this approach in my own game to preserve UI and global effects because they are common to all levels and won’t need to be reloaded everytime. One drawback is that scenes are less likely to be tested independently because they require to be in their “container” at runtime, but I worked around it somehow.

Thank you. This is very helpful.

Payotz | 2017-05-10 06:12