Skip to content
Download

Keep data between rooms

You want the player’s lives and coins to stay the same when it moves on to the next level.

When the game switches rooms, the instances of the old room go away. There are two ways to keep one alive.

A global object is created once, in the first room, and exists in all the others, without you placing an instance in each level. It is the right place for a game controller.

  1. Create an object, for example Controle, with the variables moedas (coins) and vidas (lives).
  2. Under Projeto › Configurações do projeto… (Project › Project settings), in Objetos globais (global objects), click + Objeto global and choose Controle.

From any other object, find the controller with instance:

onTouchStart<Player>([this](Player&) {
instance<Controle>()->moedas += 1;
destroy();
});

instance<Controle>() returns the first living instance of the object, or nullptr if there is none.

Check Persistente (persistent) in the object’s Inspector. The instance goes to the next room with everything it had: variables, timers, position.

Use it when the instance is already in a room and needs to come along, like the player itself.

  • restart() doesn’t recreate a persistent or global object. If the game starts over on game over, reset the lives and coins yourself.
  • The position is kept too. A persistent player arrives in the new room at the same x and y it was at. Reposition it in the code if you need to.
  • Don’t keep a pointer to another instance. It can go away when the room changes. Keep a Handle:
Handle<Enemy> alvo;
if (Enemy* perto = closest<Enemy>()) alvo = perto->handle<Enemy>();
// later:
if (Enemy* enemy = alvo.get()) enemy->destroy();